源:http://www.open-open.com/lib/view/open1348820721338.html
nginx配置结构清晰,层次分明,这得益于整个架构的模块化设计,文本将揭示配置文件如何被处理和应用。

整个配置文件解析后的结果如图这样存储。
一、解析的核心机制
nginx源码里,ngx_conf_t是解析的关键结构体
ngx_conf_handler函数里:
04 | if (cmd->type & NGX_DIRECT_CONF) { |
05 | conf = ((void **) cf->ctx)[ngx_modules[i]->index]; |
08 | } else if (cmd->type & NGX_MAIN_CONF) { |
09 | conf = &(((void **) cf->ctx)[ngx_modules[i]->index]); |
12 | confp = *(void **) ((char *) cf->ctx + cmd->conf); |
16 | conf = confp[ngx_modules[i]->ctx_index]; |
20 | rv = cmd->set(cf, cmd, conf); |
23 | { ngx_string("sendfile"), |
24 | NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |
26 | ngx_conf_set_flag_slot, |
27 | NGX_HTTP_LOC_CONF_OFFSET, |
28 | offsetof(ngx_http_core_loc_conf_t, sendfile), |
二、配置的应用
1、最简单形式,direct方式
2 | #define ngx_get_conf(conf_ctx, module) conf_ctx[module.index] |
4 | ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module); |
5 | if (ccf->master && ngx_process == NGX_PROCESS_SINGLE) { |
6 | ngx_process = NGX_PROCESS_MASTER; |
2、稍微复杂点形式,main方式
2 | #define ngx_event_get_conf(conf_ctx, module) \ |
3 | (*(ngx_get_conf(conf_ctx, ngx_events_module))) [module.ctx_index]; |
7 | epcf = ngx_event_get_conf(cycle->conf_ctx, ngx_epoll_module); |
3、不简单的http配置
02 | #define ngx_http_get_module_loc_conf(r, module) (r)->loc_conf[module.ctx_index] |
04 | ngx_http_log_loc_conf_t *lcf; |
06 | lcf = ngx_http_get_module_loc_conf(r, ngx_http_log_module); |
13 | cscf = addr_conf->default_server; |
15 | r->main_conf = cscf->ctx->main_conf; |
16 | r->srv_conf = cscf->ctx->srv_conf; |
17 | r->loc_conf = cscf->ctx->loc_conf; |
还有个要提的,http配置分main, src, loc,下级的配置可以覆盖上级,很明显,上级只是默认设置值而已。
三、重提模块化设计
学着用模块化的角度去看nginx的整体设计,一切以模块为核心,配置依赖于模块,即模块本身就携带着它的配置。正因为这样的设计的,配置文件的解析,使用非常简单。避免过多使用全局变量好像成为一种共识,但是在nginx世界里,全局变量可不少,每个模块都是个全局变量,为什么这样设计呢?因为模块之间是有依赖性的,所以需要互相访问。
配置文件解析这块的代码极具借鉴,本文只管窥般分析了配置文件,不能剥夺读者阅读源码的享受,点到即止。