向nginx中添加第一个最简单的hello world模块
一、编写ngx_http_mytest_module模块
1. ngx_http_mytest_module.c
1 #include <ngx_config.h> 2 #include <ngx_core.h> 3 #include <ngx_http.h> 4 5 //mytest module define 6 7 static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t* r) 8 { 9 //不是GET或者HEAD方法,返回405 10 if (!(r->method & (NGX_HTTP_GET | NGX_HTTP_HEAD))){ 11 return NGX_HTTP_NOT_ALLOWED; 12 } 13 //忽略接收到的包体 14 ngx_int_t rc = ngx_http_discard_request_body(r); 15 if (rc != NGX_OK) 16 return rc; 17 18 //设置响应头 19 ngx_str_t type = ngx_string("text/plain"); 20 ngx_str_t response = ngx_string("Hello World!"); 21 //设置http状态码 22 r->headers_out.status = NGX_HTTP_OK; 23 //设置响应Content-Type 24 r->headers_out.content_length_n = response.len; 25 r->headers_out.content_type = type; 26 27 //发送响应头 28 rc = ngx_http_send_header(r); 29 if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) 30 return rc; 31 32 //设置响应内容 33 ngx_buf_t* b; 34 b = ngx_create_temp_buf(r->pool, response.len); 35 if (b == NULL) 36 return NGX_HTTP_INTERNAL_SERVER_ERROR; 37 ngx_memcpy(b->pos, response.data, response.len); 38 b->last = b->pos + response.len; 39 b->last_buf = 1; 40 41 //设置响应内容到chain中 42 ngx_chain_t out; 43 out.buf = b; 44 out.next = NULL; 45 46 return ngx_http_output_filter(r, &out); 47 } 48 49 //set handler 50 static char* ngx_http_mytest(ngx_conf_t* cf, ngx_command_t* cmd, void* conf) 51 { 52 ngx_http_core_loc_conf_t* clcf; 53 clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); 54 clcf->handler = ngx_http_mytest_handler; 55 return NGX_CONF_OK; 56 } 57 58 //conf structure 59 static ngx_command_t ngx_http_mytest_commands[] = 60 { 61 { 62 ngx_string("mytest"), 63 NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | 64 NGX_HTTP_LMT_CONF | NGX_CONF_NOARGS, 65 ngx_http_mytest, 66 NGX_HTTP_LOC_CONF_OFFSET, 67 0, 68 NULL 69 }, 70 ngx_null_command 71 }; 72 73 //module ctx 74 static ngx_http_module_t ngx_http_mytest_module_ctx = { NULL, NULL, NULL, NULL, NULL, NULL,NULL, NULL}; 75 76 //mytest module 77 ngx_module_t ngx_http_mytest_module = { 78 NGX_MODULE_V1, 79 &ngx_http_mytest_module_ctx, 80 ngx_http_mytest_commands, 81 NGX_HTTP_MODULE, 82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, 83 NGX_MODULE_V1_PADDING 84 };
2.config
1 ngx_addon_name=ngx_http_mytest_module 2 HTTP_MODULES="$HTTP_MODULES ngx_http_mytest_module" 3 NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_mytest_module.c"
二、安装nginx
1 ./configure --prefix=/usr/local/nginx --add-module=/usr/local/src/ngx-mytest-module/
三、修改配置文件
1 location /test { 2 mytest; 3 }
四、启动nginx,并通过浏览器访问
五、查看日志文件
倒数第二行对/test的响应。
六、对过程一些问题的总结
1. 执行configure后,objs文件夹下ngx_modules.c文件中只有3部分:
1)extern模块
2)ngx_modules数组
3)ngx_module_names数组
2. nginx自定义模块需要添加的头文件
3. 如果主机不能访问虚拟机web服务器,可能是需要关闭防火墙
1 iptables -F 2 iptables -P INPUT ACCEPT