nginx启动时解析配置文件
nginx启动时(即nginx -c conf/nginx.conf),解析conf数据,放到模块内。
解析nginx.conf的http-block:
//conf/nginx.conf
...
http {
}
//ngx_http.c
static ngx_command_t ngx_http_commands[] = {
{ ngx_string("http"),
NGX_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS,
ngx_http_block,
0,
0,
NULL },
ngx_null_command
};
ngx_http_block 函数在nginx每个进程启动后解析conf/nginx.conf配置的时候执行一次
ngx_http_block 函数中的 ngx_http_init_phase_handlers函数初始化http状态机
http初始化流程:
- 将conf-http-block 内的key-value进行读取并初始化
//ngx_http.c
ngx_http_init_listening
//ngx_http_config.h
//下面这些回调函数执行解析conf-http-block里的配置
typedef struct {
ngx_int_t (*preconfiguration)(ngx_conf_t *cf); //读配置前
ngx_int_t (*postconfiguration)(ngx_conf_t *cf); //读配置后
void *(*create_main_conf)(ngx_conf_t *cf); //创建结构体保存http根配置
char *(*init_main_conf)(ngx_conf_t *cf, void *conf); //初始化结构体http根配置
void *(*create_srv_conf)(ngx_conf_t *cf); //创建结构体保存http-server配置
char *(*merge_srv_conf)(ngx_conf_t *cf, void *prev, void *conf); //合并多个结构体http-server配置
void *(*create_loc_conf)(ngx_conf_t *cf); //创建结构体保存http-server-location配置
char *(*merge_loc_conf)(ngx_conf_t *cf, void *prev, void *conf); //合并多个结构体http-server-location配置
} ngx_http_module_t;
- 11个阶段,http处理的状态机
//ngx_http.c
ngx_http_init_phase_handlers
//ngx_http_core_module.h
//11个状态,一个状态可以有一个或者多个模块来处理
typedef enum {
NGX_HTTP_POST_READ_PHASE = 0, //读完客户端请求
NGX_HTTP_SERVER_REWRITE_PHASE,
NGX_HTTP_FIND_CONFIG_PHASE,
NGX_HTTP_REWRITE_PHASE,
NGX_HTTP_POST_REWRITE_PHASE,
NGX_HTTP_PREACCESS_PHASE,
NGX_HTTP_ACCESS_PHASE,
NGX_HTTP_POST_ACCESS_PHASE,
NGX_HTTP_PRECONTENT_PHASE,
NGX_HTTP_CONTENT_PHASE,
NGX_HTTP_LOG_PHASE
} ngx_http_phases;
一个状态可以有一个或者多个模块来处理,如:
//ngx_http_realip_module.c
static ngx_int_t
ngx_http_realip_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);
//NGX_HTTP_POST_READ_PHASE状态push到模块的动态数组array里待处理。
h = ngx_array_push(&cmcf->phases[NGX_HTTP_POST_READ_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
//NGX_HTTP_POST_READ_PHASE状态的一个处理函数
*h = ngx_http_realip_handler;
//NGX_HTTP_PREACCESS_PHASE状态push到模块的动态数组array里待处理。
h = ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
//NGX_HTTP_PREACCESS_PHASE状态的一个处理函数
*h = ngx_http_realip_handler;
return NGX_OK;
}
大概执行流程:
ngx_http_process_request_line–>ngx_http_process_request–>ngx_http_handler–>ngx_http_core_run_phases
- tcp server
//ngx_http.c
ngx_http_block 函数中的 ngx_http_optimize_servers函数启动tcp-server