要理解 HTTP 模块配置解析的过程,首先需要对 nginx 的配置文件结构做一个了解
nginx 的配置文件是用树状结构组织的,每个 NGX_CORE_MODULE 作为根统领着其下的所有配置项
而如下图所示,HTTP 模块的配置被分成了 main、server、location 三层
整个 nginx 配置解析的过程其实就是这棵树的深度遍历过程
而遍历 HTTP 子树的函数就是下面要介绍的 ngx_http_block
配置文件解析 -- http 配置块
当我们需要使用 http 模块的时候,我们需要在配置文件中加入 http 配置块:
在 http 配置块中,我们配置了 http 连接相关的信息,HTTP 框架也正是从这里启动的.
在 nginx 初始化的过程中,执行了 ngx_init_cycle 函数,其中进行了配置文件解析,调用了 ngx_conf_parse 函数
配置文件解析
函数 ngx_conf_handler 根据配置项的 command 调用了对应的 set 回调函数
?阅读各模块的 ngx_command_t 命令配置结构,可以找到:
?
http 配置块解析 -- ngx_http_block
在解析到 http 配置块时,执行了对应的 set 回调函数 ngx_http_block
?这个函数中,为所有的 http 模块都分配并创建了配置结构,同时,调用了每个模块相应的初始化回调。
最后,调用 ngx_http_optimize_servers 创建了 http 连接,加入 cycle 的监听数组,并设为监听状态。
nginx 配置文件对 http 模块的配置分为三层:main、sever、location,因此,http 模块上下文 ngx_http_module_t 中定义了以下六个回调函数,用来创建和保存配置信息:
- create_main_conf
- init_main_conf
- create_srv_conf
- merge_srv_conf
- create_loc_conf
- merge_loc_conf
在 ngx_http_block 中,循环调用了所有 NGX_HTTP_MODULE 的这六个回调函数,创建相关的配置结构。
server、location 配置解析 -- ngx_http_core_server、ngx_http_core_location
在调用所有 HTTP 模块的 create_main_conf、create_srv_conf、create_loc_conf 后,所有需要配置结构的模块都完成了配置结构的创建,于是在调用所有模块的 preconfiguration 回调函数后,配置解析工作正式展开
通过调用 ngx_conf_parse 函数,开始了 http 配置块的解析,并通过解析到的命令调用相应的函数
在首个 NGX_HTTP_MODULE ngx_http_core_module 的 ngx_command_t 域中包含了大量的配置指令,它们都是在http{}块中出现的,其中包括两个重要的指令:
?这里配置了 listen、server 与 location 块的解析函数 ngx_http_core_listen、ngx_http_core_server 和 ngx_http_core_location.
server 块解析 -- ngx_http_core_server
location 块解析 -- ngx_http_core_location
?与 server 块解析函数 ngx_http_core_server 类似,他创建了所有模块的 loc_conf,为了防止内外层具有相同指令,在配置赋值完成后,会通过 merge 函数合并到一起。
然而,与 server 块不同,location 块在 location 后面会通过路径或正则表达式指定 location 配置的应用 uri,因此,在 ngx_http_core_location 函数中调用 PCRE 进行了 location 命令的解析。
解析完成后调用 ngx_http_add_location 将解析结果加入到 locations 链表中。
?配置解析全部完成后的配置结构。