开发第一个Nginx模块
首先在/src下建立文件夹mymodule
配置config文件
config文件实际上是shell脚本
开发一个HTTP模块需要包含如下变量
#仅仅在configure使用,一般是模块名
ngx_addon_name=ngx_mymodule
#保存所有模块名的数组,不能直接赋值覆盖,因为还有其他模块在里面
HTTP_MODULES="$HTTP_MODULES ngx_http_mymodule_module"
#新增模块的源码文件
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_mymodule_module.c"
在/src/mymodule/下创建源文件ngx_http_mymodule_module.c,必须和上面配置的一样
测试下
#执行configure使用--add-module=src/mymodule添加自己开发的模块 ./configure --add-module=src/mymodule/ --without-http_rewrite_module --without-http_gzip_module
configures
可见已经添加了mymodule模块,由于还没有写代码,就不make install了
编写自己的模块(C语言版本)
大致流程
1,nginx读取到配置文件时,发现mymodule模块
2,调用ngx_http_mymodule_commands指定的ngx_http_mymodule回调函数
3,ngx_http_mymodule回调时设置处理HTTP的回调函数ngx_http_mymodule_handler
- 首先引入需要的nginx核心模块
```
#include
#include
#include
#include
#include
#include
- 定义一个Nginx的HTTP模块 ngx_module_t,结构体说明如下:
struct ngx_module_s {
//表示当前模块在这类模块中的序号,对于所有http模块,
//ctx_index是由核心模块ngx_http_module设置的
//表达优先级和模块位置
ngx_uint_t ctx_index;
//表示当前模块在所有模块中的序号
ngx_uint_t index;
//保留字段,未使用
ngx_uint_t spare0;
ngx_uint_t spare1;
ngx_uint_t spare2;
ngx_uint_t spare3;
//版本,目前只有1
ngx_uint_t version;
//用于指向一类模块的上下文结构体,模块上下文。指向特定类型模块的公共接口
void *ctx;
//将处理nginx.conf中的配置项
ngx_command_t *commands;
//模块类型,HTTP_FILTER_MODULES,CORE_MODULES,EVENT_MODULES,HTTP_MODULES,HTTP_HEADERS_FILER_MODULE
//HTTP_FILTER_MODULES --> http过滤模块
//
//CORE_MODULES --> 核心模块
//
//EVENT_MODULES --> 事件模块
//
//HTTP_MODULES --> HTTP模块
//
//HTTP_HEADERS_FILER_MODULE --> HTTP头部过滤模块
//还可以自定义新的模块
ngx_uint_t type;
/**
* 七个重要的模块回调点
*/
//master进程启动时调用,但是目前框架从不调用,因此直接设置成NULL就行
ngx_int_t (*init_master)(ngx_log_t *log);
//初始化所有模块时被调用,master/worker模式下,在启动worker前完成
ngx_int_t (*init_module)(ngx_cycle_t *cycle);
//worker子进程已经产生,每个worker进程初始化过程会调用所有模块的init_process
ngx_int_t (*init_process)(ngx_cycle_t *cycle);
//由于nginx不支持多线程模式,所以init_thread在框架中没被调用过<