|零基础开发 nginx 模块( 三 )


首先引入 nginx 头文件 , 声明模块入口 ngx_module_t 对象 , 变量名必须为 config 脚本中配置的模块名 , 本例中即为 ngx_http_hello_module。
#include #include #include extern ngx_module_t ngx_http_hello_module;接下来设置 HTTP 模块信息 ngx_http_module_t, 相关处理函数全部设置为 NULL。
static ngx_http_module_t ngx_http_hello_module_ctx = { NULL,/* preconfiguration */ NULL,/* postconfiguration */ NULL,/* create main configuration */ NULL,/* init main configuration */ NULL,/* create server configuration */ NULL,/* merge server configuration */ NULL,/* create location configuration */ NULL/* merge location configuration */ };指令列表 ngx_command_t[] 设置为一个空列表 , 仅包含 ngx_null_command 结尾标记 。
static ngx_command_t ngx_http_hello_commands[] = { ngx_null_command };最后 , 定义模块入口对象 ngx_module_t。 开头私有字段使用 NGX_MODULE_V1 表示 , 结尾扩展备用字段使用 NGX_MODULE_V1_PADDING 表示 。 设置上述定义的 HTTP 模块信息 ngx_http_hello_module_ctx 和指令列表 ngx_http_hello_commands, 生命周期管理函数全部设置为 NULL。
ngx_module_t ngx_http_hello_module = { NGX_MODULE_V1, &ngx_http_hello_module_ctx,/* module context */ ngx_http_hello_commands,/* module directives */ NGX_HTTP_MODULE,/* module type */ NULL,/* init master */ NULL,/* init module */ NULL,/* init process */ NULL,/* init thread */ NULL,/* exit thread */ NULL,/* exit process */ NULL,/* exit master */ NGX_MODULE_V1_PADDING };至此 , 一个空模块开发完成 。 这可以作为开发 HTTP 模块的初始模板 , 我们将在此基础上逐渐增加功能 。
在 nginx 代码仓库目录下执行 make modules, 即可重新编译生成动态模块文件 objs/ngx_http_hello_module.so。 因为我们没有修改模块配置 , 没有添加或删除源码文件 , 所以不需要重新执行 auto/configure 配置脚本 , 直接执行 make modules 即可 。
测试运行 nginx
在 nginx 代码仓库目录下新建一个测试配置文件 objs/nginx.conf, 内容如下:
# vim: set ft=nginx et: daemon off;# default on pid objs/nginx.pid; error_log stderr notice; load_module objs/ngx_http_hello_module.so; events { } http { access_log objs/access.log; server { listen 8080 default_server; return 200 ''testn''; } }

  • daemon off; 设置 nginx 进程不要后台化 , 保持前台运行 , 按 Ctrl+C 即可退出 nginx。
  • error_log stderr notice; 错误日志直接输出到终端 , 方便测试运行时查看错误日志 , 设置日志级别为 notice。
  • load_module objs/ngx_http_hello_module.so; 加载我们开发的动态模块 ngx_http_hello_module.so。
  • listen 8080 default_server; HTTP 服务器监听 8080 端口 , 这样使用普通用户即可运行测试 。
  • return 200 ''testn''; HTTP 请求直接返回 ''test'' 字符串 。
在 nginx 代码仓库目录下使用如下命令测试运行 nginx。
objs/nginx -p ''$PWD'' -c objs/nginx.conf
  • -p ''$PWD'' 设置 nginx prefix 为当前目录 。 配置文件路径和配置文件中使用的相对路径使用相对于 prefix 的路径 。
  • -c objs/nginx.conf 设置配置文件路径 。
可看到 nginx 启动并打印日志 , 按 Ctrl+C 后 nginx 退出 。 此时我们的模块还是空模块 , 没有发挥任何作用 。
Nginx 配置指令 - 世界你好
当我们学习一种新的开发技术时 , 第一个程序通常是 ''hello world'': 打印一条 ''hello world'' 语句 , 向世界问声好 。 第一次接触 nginx 开发时 , 我们不得不花时间做一些准备工作 。 现在 , 终于是时候张开双臂 , 说一声 ''世界你好'' 了 。


推荐阅读