深度剖析 Nginx 啟動階段配置文件解析核心流程:ngx_init_cycle → ngx_conf_parse → 模塊配置創建、合併、階段初始化。
ngx_cycle_t,初始化成員。create_conf → 生成 ngx_core_conf_t 存入 cycle->conf_ctx。ngx_conf_t 解析上下文。ngx_conf_parse 遞歸解析配置文件,結果存入各模塊 conf 結構。init_conf:對未設值 (=-1) 賦予默認值。ngx_open_listening_sockets:遍歷 listening 數組,socket→setsockopt→bind→listen。init_module (僅 ngx_event_module_init 實現)。循環讀取指令 → 匹配命令表 → 調用對應 set 處理函數 → 寫入模塊配置結構體偏移位置。
指令如 daemon,set 為 ngx_conf_set_flag_slot,直接操作 ngx_core_conf_t 成員。
events { },set 為 ngx_events_block。ngx_event_conf_t 及各事件模塊 (epoll/kqueue) 配置結構。events 塊內指令。http { },set 為 ngx_http_block。ngx_http_conf_ctx_t,含 main_conf、srv_conf、loc_conf 三層數組。create_main_conf/srv_conf/loc_conf 填充三層數組。preconfiguration 鉤子。http 塊:main 指令寫入 main_conf (如 variables_hash_max_size)server 指令:複製 main_conf、新建 srv_conf/loc_conf 進入 server 上下文location 指令:繼承 main/srv、新建 loc_conf 進入 location 上下文ngx_http_block:調用 init_main_conf、ngx_http_merge_servers 合併 server/location 配置。
struct ngx_command_s {
ngx_str_t name; // 指令名
ngx_uint_t type; // 參數類型、作用域標誌
char *(*set)(ngx_conf_t*, ngx_command_t*, void*); // 處理函數
ngx_uint_t conf; // 配置結構相對偏移 (NGX_HTTP_MAIN_CONF_OFFSET 等)
ngx_uint_t offset; // 成員在結構體內偏移
void *post; // 後處理回調
};
conf + offset 精確定位目標成員地址,實現通用配置寫入。
