> 文章列表 > nginx http模块

nginx http模块

nginx http模块

  1. 模块依赖

nginx http模块

2. 模块的初始化

nginx http模块

2.1 location的定义

location的定义包含以下几种

location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }

=:表示精确匹配,只有请求的url路径与后面的字符串完全相等时,才会命中,不支持location嵌套

~:表示使用正则定义的,区分大小写

~*:表示是使用正则定义的,不区分大小写

^~:表示该符号后面的字符是最佳匹配,采用该规则,不再进行后续的查找

@name:用于定义一个内部 Location 块,该块不能被外部 Client 所访问,只能被 NGINX 内部配置指令所访问,比如 try_files 或者error_page。其修饰的location不能嵌套到其它location,也不能再嵌套其它location,即只能是server这一层的

2.2 分配ngx_http_conf_ctx_t

2.2.1 ngx_http_block

其是在解析配置文件中的http分配

ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
ctx->main_conf = ngx_pcalloc(cf->pool,sizeof(void *) * ngx_http_max_module);
ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);

2.2.2 ngx_http_core_location

其是在解析配置文件中的http块内location时分配

其中main_conf,srv_conf是延用上一层级的,loc_conf会再一次分配内存

ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
pctx = cf->ctx;
ctx->main_conf = pctx->main_conf;
ctx->srv_conf = pctx->srv_conf;
ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);

同时也会遍历模块调用create_loc_conf创建location的配置

for (i = 0; cf->cycle->modules[i]; i++) {if (cf->cycle->modules[i]->type != NGX_HTTP_MODULE) {continue;}module = cf->cycle->modules[i]->ctx;if (module->create_loc_conf) {ctx->loc_conf[cf->cycle->modules[i]->ctx_index] =module->create_loc_conf(cf);if (ctx->loc_conf[cf->cycle->modules[i]->ctx_index] == NULL) {return NGX_CONF_ERROR;}}}

设置http_core_module配置的loc_conf来源

clcf = ctx->loc_conf[ngx_http_core_module.ctx_index];
clcf->loc_conf = ctx->loc_conf;

2.3 ngx_http_add_location

构造ngx_http_location_queue_t,将当前ngx_http_core_loc_conf_t添加到上一层级ngx_http_core_loc_conf_t中的location队列中。如果是精确匹配,正则,有名或者是无名,构造的ngx_http_location_queue_t的exact来存放ngx_http_core_loc_conf_t配置,否则使用ngx_http_location_queue_t的inclusive来存放ngx_http_core_loc_conf_t配置

if (clcf->exact_match
#if (NGX_PCRE)|| clcf->regex
#endif|| clcf->named || clcf->noname){lq->exact = clcf;lq->inclusive = NULL;} else {lq->exact = NULL;lq->inclusive = clcf;}

将构造的队列添加到上一层级的队列中

ngx_queue_insert_tail(*locations, &lq->queue);

2.4 主配置中的server

在ngx_http_block中会分配main_conf

ctx->main_conf = ngx_pcalloc(cf->pool,sizeof(void *) * ngx_http_max_module);

在处理server时(ngx_http_core_server),当前层的ctx中的main_conf会延用上一层的main_conf

http_ctx = cf->ctx;
ctx->main_conf = http_ctx->main_conf;

将server放入cmcf->server中

cscf = ctx->srv_conf[ngx_http_core_module.ctx_index];
cscf->ctx = ctx;cmcf = ctx->main_conf[ngx_http_core_module.ctx_index];cscfp = ngx_array_push(&cmcf->servers);
if (cscfp == NULL) {return NGX_CONF_ERROR;
}*cscfp = cscf;