nginx HTTP 的 11 个阶段
nginx 源码的特点是用了很多回调函数,阅读起来非常麻烦,因为不知道当前这个 hanlder 到底对应哪个函数。 在正式开始研究这 11 个阶段之前,我们先看几个结构体,然后再看 ngx_http_core_run_phases() 函数,希望能更快的理解这些 phase 是怎么 run 的。 ngx_http_core_main_conf_t 回顾一下 ngx_http_core_main_conf_t,在前面的博客中已经介绍过,它还有两个兄弟 ngx_http_core_srv_conf_t 和 ngx_http_core_loc_conf_t。 ngx_http_core_main_conf_t 中有两个成员是本文比较关心的: phase_engine 和 phases。 typedef struct { ngx_array_t handlers; } ngx_http_phase_t; typedef struct { // 所有的http请求都要使用这个引擎处理 ngx_http_phase_engine_t phase_engine; // http handler模块需要向这个数组添加元素 ngx_http_phase_t phases[NGX_HTTP_LOG_PHASE + 1]; } ngx_http_core_main_conf_t; 配置解析后的 postconfiguration 里向cmcf->phases数组添加元素,phases数组存放了所有的phase,其中每个元素是ngx_http_phase_t类型的,表示的就是对应的phase handler的数组。ngx_http_core_main_conf_t->phases数组主要用于handler的注册。 ngx_http_phase_engine_t typedef struct { ngx_http_phase_handler_t *handlers; ngx_uint_t server_rewrite_index; ngx_uint_t location_rewrite_index; } ngx_http_phase_engine_t; ngx_http_phase_handler_t struct ngx_http_phase_handler_s { ngx_http_phase_handler_pt checker; ngx_http_handler_pt handler; ngx_uint_t next; }; 看完了相关数据结构,特别是看到 checker、handler 的时候,是不是突然觉得熟悉了?没错,这就是上一篇博客 http 请求处理流程中,最后的 run core phase。 ngx_http_core_run_phases(ngx_http_request_t *r){ ngx_http_phase_handler_t *ph; ngx_http_core_main_conf_t *cmcf; cmcf = ngx_http_get_module_main_conf(r, ngx_http_core_module); ph = cmcf->phase_engine.handlers; while (ph[r->phase_handler].checker) { rc = ph[r->phase_handler].checker(r, &ph[r->phase_handler]); } } phase_engine[] 中的成员 看了上面的代码不禁有疑问:phase_engine[] 的成员是在哪赋值的呢?答案是 ngx_http_init_phase_handlers() ...