要理解 HTTP 模塊配置解析的過(guò)程,首先需要對(duì) nginx 的配置文件結(jié)構(gòu)做一個(gè)了解
nginx 的配置文件是用樹(shù)狀結(jié)構(gòu)組織的,每個(gè) NGX_CORE_MODULE 作為根統(tǒng)領(lǐng)著其下的所有配置項(xiàng)
而如下圖所示,HTTP 模塊的配置被分成了 main、server、location 三層

整個(gè) nginx 配置解析的過(guò)程其實(shí)就是這棵樹(shù)的深度遍歷過(guò)程
而遍歷 HTTP 子樹(shù)的函數(shù)就是下面要介紹的 ngx_http_block
配置文件解析 -- http 配置塊
當(dāng)我們需要使用 http 模塊的時(shí)候,我們需要在配置文件中加入 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 連接相關(guān)的信息,HTTP 框架也正是從這里啟動(dòng)的.
在 nginx 初始化的過(guò)程中,執(zhí)行了 ngx_init_cycle 函數(shù),其中進(jìn)行了配置文件解析,調(diào)用了 ngx_conf_parse 函數(shù)
配置文件解析
函數(shù) ngx_conf_handler 根據(jù)配置項(xiàng)的 command 調(diào)用了對(duì)應(yīng)的 set 回調(diào)函數(shù)
// static ngx_int_t ngx_conf_handler(ngx_conf_t *cf, ngx_int_t last)// 配置項(xiàng)解析 {{{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 命令配置結(jié)構(gòu),可以找到:
// static ngx_command_t ngx_http_commands// http 模塊命令結(jié)構(gòu) {{{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 配置塊時(shí),執(zhí)行了對(duì)應(yīng)的 set 回調(diào)函數(shù) ngx_http_block
新聞熱點(diǎn)
疑難解答
圖片精選