作者因业务需要开始涉足 nginx 模块开发,并分享了自己写的第一个 hello world 模块。nginx 模块开发相对容易,网上已有大量开源模块可借鉴,甚至有 OAuth 模块。与 Apache 加载 so 模块不同,nginx 是把模块直接编译进主程序,因此速度优势明显——简单业务逻辑的模块实测能到 1-2w 请求/秒,而 PHP 能压到 5000/s 就已不错,且部署和编译都很简单。但目前相关资料仍偏少,开发过程磕磕绊绊,建议只在业务逻辑比较简单时再考虑用于生产环境。
教程给出完整 demo:先新建 config 文件告知主程序编译该模块(注意模块名与源码位置),再编写 ngx_hello_world_module.c,实现命令定义(ngx_hello_world 指令)、模块上下文、ngx_module_t 结构,以及 handler:校验 GET/HEAD 方法、丢弃请求体、设置 content_type 为 text/html、构造 ngx_buf_t 输出 "Hello World!",最后在配置函数中向 clcf->handler 注册该 handler。编译时无需单独编译模块,只需在 nginx 的 ./configure 中加 --add-module 指向模块目录,另因 rewrite 依赖 pcre,需预先安装并可用 --with-cc-opt/--with-ld-opt 指定 pcre 路径。编译完成后模块即与主程序"合体",在 nginx.conf 的 server 块中加入 location /hello { ngx_hello_world; } 启动即可看到输出,还可与 PHP 版 Hello World 压测对比性能。