【Nginx】第一个程序Hello World
要注意,先关闭Nginx再添加第三方的模块,负责会编译不进去,我被这个地方坑了好久。
关闭命令:/usr/local/nginx/sbin/nginx -s quit
然后才是:
./configure --prefix=/usr/local/nginx --add-module=/root/coding/nginxcode
make
sudo make install
最后启动Nginx:/usr/local/nginx/sbin/nginx
测试结果:
centos虚拟机下:
windows下:
附件:
location:
location /test {
mytest;
}
config文件:
ngx_addon_name=ngx_http_mytest_module HTTP_MODULES="$HTTP_MODULES ngx_http_mytest_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_mytest_module.c"
ngx_http_mytest_module.c文件:
1 #include <ngx_config.h> 2 #include <ngx_core.h> 3 #include <ngx_http.h> 4 5 static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r); 6 static char * 7 ngx_http_mytest(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); 8 //处理配置项 9 static ngx_command_t ngx_http_mytest_commands[] = { 10 { 11 ngx_string("mytest"), 12 NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF|NGX_CONF_NOARGS, 13 ngx_http_mytest, 14 NGX_HTTP_LOC_CONF_OFFSET, 15 0, 16 NULL 17 }, 18 ngx_null_command 19 }; 20 //模块上下文 21 static ngx_http_module_t ngx_http_mytest_module_ctx = { 22 NULL, 23 NULL, 24 NULL, 25 NULL, 26 NULL, 27 NULL, 28 NULL, 29 NULL 30 }; 31 //新模块定义 32 ngx_module_t ngx_http_mytest_module = { 33 NGX_MODULE_V1, 34 &ngx_http_mytest_module_ctx, 35 ngx_http_mytest_commands, 36 NGX_HTTP_MODULE, 37 NULL, 38 NULL, 39 NULL, 40 NULL, 41 NULL, 42 NULL, 43 NULL, 44 NGX_MODULE_V1_PADDING 45 }; 46 47 //配置项对应的回调函数 48 static char * 49 ngx_http_mytest(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) 50 { 51 ngx_http_core_loc_conf_t *clcf; 52 53 clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); 54 55 clcf->handler = ngx_http_mytest_handler; 56 57 return NGX_CONF_OK; 58 } 59 60 //实际完成处理的回调函数 61 static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r) 62 { 63 if (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD))) { 64 return NGX_HTTP_NOT_ALLOWED; 65 } 66 67 ngx_int_t rc = ngx_http_discard_request_body(r); 68 if (rc != NGX_OK) { 69 return rc; 70 } 71 72 ngx_str_t type = ngx_string("text/plain"); 73 ngx_str_t response = ngx_string("Hello World"); 74 r->headers_out.status = NGX_HTTP_OK; 75 r->headers_out.content_length_n = response.len; 76 r->headers_out.content_type = type; 77 78 rc = ngx_http_send_header(r); 79 if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { 80 return rc; 81 } 82 83 ngx_buf_t *b; 84 b = ngx_create_temp_buf(r->pool, response.len); 85 if (b == NULL) { 86 return NGX_HTTP_INTERNAL_SERVER_ERROR; 87 } 88 89 ngx_memcpy(b->pos, response.data, response.len); 90 b->last = b->pos + response.len; 91 b->last_buf = 1; 92 93 ngx_chain_t out; 94 out.buf = b; 95 out.next = NULL; 96 97 return ngx_http_output_filter(r, &out); 98 }