教程 > nginx 教程 > 阅读:19

nginx handler 模块的挂载——迹忆客-ag捕鱼王app官网

handler 模块真正的处理函数通过两种方式挂载到处理过程中,一种方式就是按处理阶段挂载;另外一种挂载方式就是按需挂载。


按处理阶段挂载

为了更精细地控制对于客户端请求的处理过程,nginx 把这个处理过程划分成了 11 个阶段。他们从前到后,依次列举如下:

  • ngx_http_post_read_phase: 读取请求内容阶段
  • ngx_http_server_rewrite_phase: server 请求地址重写阶段
  • ngx_http_find_config_phase: 配置查找阶段:
  • ngx_http_rewrite_phase: location 请求地址重写阶段
  • ngx_http_post_rewrite_phase: 请求地址重写提交阶段
  • ngx_http_preaccess_phase: 访问权限检查准备阶段
  • ngx_http_access_phase: 访问权限检查阶段
  • ngx_http_post_access_phase: 访问权限检查提交阶段
  • ngx_http_try_files_phase: 配置项 try_files 处理阶段
  • ngx_http_content_phase: 内容产生阶段
  • ngx_http_log_phase: 日志模块处理阶段

一般情况下,我们自定义的模块,大多数是挂载在 ngx_http_content_phase 阶段的。挂载的动作一般是在模块上下文调用的 postconfiguration 函数中。

**注意**:有几个阶段是特例,它不调用挂载地任何的handler,也就是你就不用挂载到这几个阶段了:

  • ngx_http_find_config_phase
  • ngx_http_post_access_phase
  • ngx_http_post_rewrite_phase
  • ngx_http_try_files_phase

所以其实真正是有 7 个 phase 你可以去挂载 handler。

挂载的代码如下(摘自 hello module):

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);
        h = ngx_array_push(&cmcf->phases[ngx_http_content_phase].handlers);
        if (h == null) {
                return ngx_error;
        }
        *h = ngx_http_hello_handler;
        return ngx_ok;
}

使用这种方式挂载的 handler 也被称为 content phase handlers

按需挂载

以这种方式挂载的 handler 也被称为 content handler

当一个请求进来以后,nginx 从 ngx_http_post_read_phase 阶段开始依次执行每个阶段中所有 handler。执行到 ngx_http_content_phase 阶段的时候,如果这个 location 有一个对应的 content handler 模块,那么就去执行这个 content handler 模块真正的处理函数。否则继续依次执行 ngx_http_content_phase 阶段中所有 content phase handlers,直到某个函数处理返回 ngx_ok 或者 ngx_error

换句话说,当某个 location 处理到 ngx_http_content_phase 阶段时,如果有 content handler 模块,那么 ngx_http_content_phase 挂载的所有 content phase handlers 都不会被执行了。

但是使用这个方法挂载上去的 handler 有一个特点是必须在 ngx_http_content_phase 阶段才能执行到。如果你想自己的 handler 在更早的阶段执行,那就不要使用这种挂载方式。

那么在什么情况会使用这种方式来挂载呢?一般情况下,某个模块对某个 location 进行了处理以后,发现符合自己处理的逻辑,而且也没有必要再调用 ngx_http_content_phase 阶段的其它 handler 进行处理的时候,就动态挂载上这个 handler。

下面来看一下使用这种挂载方式的具体例子(摘自 emiller's guide to nginx module development)。

static char *
ngx_http_circle_gif(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_circle_gif_handler;
        return ngx_conf_ok;
}

查看笔记

扫码一下
查看教程更方便
网站地图