1.首先在nginx启动时,读取在编译时add-module指定的目录下的配置文件中指定的moudle name对应ngx_http_module_t变量。
如在ngx_module_test模块的目录下的配置文件为:
ngx_addon_name=ngx_module_test
HTTP_MODULES="$HTTP_MODULES ngx_module_test"NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_module_test.c"
则nginx启动时处理add-module时会先找ngx_module_test.c中变量名为ngx_module_test的ngx_module_t结构。
2.根据ngx_module_t结构->ngx_command_t结构->初始化函数指针找到初始化函数进行初始化。
所以ngx_module_test.c至少需要有如下亦是定义:
a.ngx_module_t ngx_module_test.定义模块入口和需要的参数:
ngx_module_t ngx_module_test = {
NGX_MODULE_V1,
&ngx_test_module_ctx, /* module context */
ngx_test_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
};
b.ngx_http_module_t ngx_test_module_ctx用于将nginx环境传递给handler
static ngx_http_module_t ngx_test_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_test_create_loc_conf, /* create location configuration */
ngx_test_merge_loc_conf /* merge location configuration */
};
c.用来初始化和注册handler的ngx_command_t ngx_test_commands数组,可以同时加载多个:
static ngx_command_t ngx_test_commands[] = {
{ ngx_string("test"),
NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1,
ngx_test_init,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_test_loc_conf_t, ecdata),
NULL},
ngx_null_command
};
d.char * ngx_test_init,处理初始化和注册handler的函数指针
static char * ngx_test_init(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_test_handler; //在这里注册我们的handler,同时传入相关的上下文
ngx_conf_set_str_slot(cf, cmd, conf);
return NGX_CONF_OK;
}
e.主要的处理逻辑 static ngx_int_t ngx_test_handler(ngx_http_request_t *r)