要理解 HTTP 模塊配置解析的過程,首先需要對 nginx 的配置文件結構做一個了解
nginx 的配置文件是用樹狀結構組織的,每個 NGX_CORE_MODULE 作為根統領著其下的所有配置項
而如下圖所示,HTTP 模塊的配置被分成了 main、server、location 三層
整個 nginx 配置解析的過程其實就是這棵樹的深度遍歷過程
而遍歷 HTTP 子樹的函數就是下面要介紹的 ngx_http_block
配置文件解析 -- http 配置塊
當我們需要使用 http 模塊的時候,我們需要在配置文件中加入 http 配置塊:
http { // http 配置塊 {{{ include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; server { listen 8001; server_name localhost; #autoindex on; #charset koi8-r; #access_log logs/host.access.log main; location / { root /var/www/; index index.html index.htm index.php;
在 http 配置塊中,我們配置了 http 連接相關的信息,HTTP 框架也正是從這里啟動的.
在 nginx 初始化的過程中,執行了 ngx_init_cycle 函數,其中進行了配置文件解析,調用了 ngx_conf_parse 函數
配置文件解析
函數 ngx_conf_handler 根據配置項的 command 調用了對應的 set 回調函數
// static ngx_int_t ngx_conf_handler(ngx_conf_t *cf, ngx_int_t last)// 配置項解析 {{{static ngx_int_tngx_conf_handler(ngx_conf_t *cf, ngx_int_t last){ char *rv; void *conf, **confp; ngx_uint_t i, found; ngx_str_t *name; ngx_command_t *cmd; name = cf->args->elts; found = 0; for (i = 0; ngx_modules[i]; i++) { cmd = ngx_modules[i]->commands; if (cmd == NULL) { continue; } for ( /* void */ ; cmd->name.len; cmd++) { if (name->len != cmd->name.len) { continue; } if (ngx_strcmp(name->data, cmd->name.data) != 0) { continue; }
閱讀各模塊的 ngx_command_t 命令配置結構,可以找到:
// static ngx_command_t ngx_http_commands// http 模塊命令結構 {{{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}; // }}}
http 配置塊解析 -- ngx_http_block
在解析到 http 配置塊時,執行了對應的 set 回調函數 ngx_http_block
新聞熱點
疑難解答