Nginx handle的两种挂载方式。
一:按阶段挂载
这种挂载是在postconfiguration函数执行时添加到ngx_http_core_main_conf_t. phases[]. handlers里。
static ngx_http_module_t ngx_http_hello_module_ctx = {
NULL, /* preconfiguration */
ngx_http_hello_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_hello_create_loc_conf, /* create location configuration */
NUL
}
static ngx_int_t
ngx_http_hello_init(ngx_conf_t *cf)
{
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); //取得core_module的cf
h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers); // 挂载函数到对应处理阶段
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_hello_handler; //将函数指针指向handler函数
return NGX_OK;
}
二:按需求添加
static char *
ngx_http_mytest(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_http_mytest_handler;
return NGX_CONF_OK;
}
这种方式只能在NGX_HTTP_CONTENT_PHASE阶段执行,ngx_http_core_content_phase执行时,优先处理这种挂载。一旦判断有这种挂载存在,第一种的挂载handle将不会被执行。
ngx_http_update_location_config 中有会把handle赋值给content_handler.ngx_http_request_t->content_handler = clcf->handler;
然后执行的时优先执行这种挂载。
ngx_int_t
ngx_http_core_content_phase(ngx_http_request_t *r,
ngx_http_phase_handler_t *ph)
{
size_t root;
ngx_int_t rc;
ngx_str_t path;
if (r->content_handler) {
r->write_event_handler = ngx_http_request_empty_handler;
ngx_http_finalize_request(r, r->content_handler(r));
return NGX_OK;
}