Nginx Handler模块用于在content phase直接生成响应,需实现ngx_http_handler_pt函数并注册到ngx_http_module_t的handler字段;以ngx_http_hello_module为例,通过自定义指令控制启用,在/hello路径返回"Hello, World!",支持扩展动态内容如解析参数、输出JSON,但不可阻塞。

要写一个 Nginx Handler 模块来生成简单内容,核心是注册自己的 handler 函数,在请求匹配时直接输出响应,不走 upstream 或文件系统。它比 Filter 模块更底层,适合做轻量动态内容(比如状态页、调试信息、固定 JSON 接口)。
理解 Handler 模块的生命周期
Nginx 在处理一个请求时,会按阶段(phase)调用对应模块。Handler 模块通常挂载在 content phase,一旦某个 handler 被执行并返回 NGX_OK / NGX_HTTP_* 状态码,后续 content handler 就不再运行(除非显式跳过)。所以你的模块必须能“接管”响应流程。
关键点:
- 必须实现
ngx_http_handler_pt类型的函数,作为入口 - 需在模块的
ngx_http_module_t中将该函数赋给handler字段 - 通常配合自定义指令(如
hello_world on;)控制启用,或通过 location 匹配自动触发
编写最小可运行模块:hello_world
以输出 "Hello, World!" 为例,模块名为 ngx_http_hello_module:
- 定义配置结构体(哪怕为空),声明指令表(例如只支持
hello_world开关) - 实现
ngx_http_hello_handler:设置响应头(r->headers_out.content_type)、状态码(NGX_HTTP_OK)、分配响应体缓冲区(ngx_create_temp_buf)、拷贝字符串、调用ngx_http_send_header和ngx_http_output_filter - 在
ngx_http_hello_commands中注册指令,解析后存入 loc 配置,供 handler 判断是否生效 - 编译时链接到 Nginx:添加到
auto/modules或用--add-module=参数
编译与配置验证
模块源码写好后,进入 Nginx 源码目录执行:
./configure --add-module=/path/to/ngx_http_hello_module && make && sudo make install
然后在 nginx.conf 的某个 location 中启用:
location /hello {
hello_world on;
}
启动 Nginx 后访问 http://localhost/hello,应直接返回纯文本 "Hello, World!",且响应头中 Content-Length 正确,无多余日志或重定向。
扩展思路:返回动态内容
Handler 可读取 Nginx 变量(如 $arg_name、$time_local)、获取请求头、甚至调用简单 C 函数生成 JSON:
- 用
ngx_http_arg解析 URL 参数 - 用
ngx_sprintf构造格式化字符串(注意缓冲区大小) - 设置
r->headers_out.content_type.len = ngx_string("application/json"); - 避免在 handler 中做阻塞 I/O 或复杂计算——它运行在 event loop 主线程,影响吞吐

















