Nginx Http框架的理解
HTTP框架是Nginx基础框架的一部分,Nginx的其它底层框架如master-worker进程模型、event模块、mail 模块等。
HTTP框架代码主要有2个模块组成:ngx_http_module和ngx_http_core_module;
我们编写的HTTP模块需要注册到HTTP框架上,才能融入HTTP请求的处理流程中。
当在nginx.conf中存在一个http{...}的配置时,即启用了HTTP框架代码,在nginx配置解析时,就已经为框架建立好了各种数据结构(尤其是HTTP模块的挂载);
当nginx收到请求时,请求完全按照HTTP框架建立好的这种逻辑进行处理。
一、HTTP模块开发基础
开发一个HTTP模块,需要下面几个数据结构:
这些回调是在ngx_http_block()解析http{...}配置时完成的:
当遇到一个 http{...} 时,HTTP框架会调用所有HTTP模块可能实现的create_main_conf、create_srv_conf、create_loc_conf生成存储main级别配置参数结构体;
当遇到一个server{...}时,HTTP框架会调用所有HTTP模块可能实现的create_srv_conf、create_loc_conf生成存储server级别配置参数结构体;
当遇到一个location{...}时,HTTP框架会调用所有HTTP模块可能实现的create_loc_conf生成存储location级别配置参数结构体;
因此,我们开发的HTTP模块中create_loc_conf方法被调用的次数等于http{...}、server{...}、location{...}在nginx.conf出现的次数之和;
create_srv_conf方法被调用的次数等于server{...}、location{...}在nginx.conf出现的次数之和;
由于只有一个http{...},所以create_main_conf方法只会被调用一次;
HTTP创建了如此多的结构体来存放配置项,是为了解决同名配置项的合并问题。
struct ngx_module_s {
ngx_uint_t ctx_index; //
在所有的HTTP模块中的序列号
ngx_uint_t index; // 在所有模块中的序列号
ngx_uint_t spare0;
ngx_uint_t spare1;
ngx_uint_t spare2;
ngx_uint_t spare3;
ngx_uint_t version;
void *ctx; // 模块上下文
ngx_command_t
*commands; // 模块配置指令
ngx_uint_t type; //
模块类型,HTTP模块应为NGX_HTTP_MODULE
ngx_int_t (*init_master)(ngx_log_t *log);
ngx_int_t (*init_module)(ngx_cycle_t *cycle);
ngx_int_t (*init_process)(ngx_cycle_t *cycle);
ngx_int_t (*init_thread)(ngx_cycle_t *cycle);
void
(*exit_thread)(ngx_cycle_t *cycle);
void
(*exit_process)(ngx_cycle_t *cycle);
void (*exit_master)(ngx_cycle_t *cycle);
uintptr_t spare_hook0;
uintptr_t
spare_hook1;
uintptr_t spare_hook2;
uintptr_t
spare_hook3;
uintptr_t spare_hook4;
uintptr_t spare_hook5;
uintptr_t
spare_hook6;
uintptr_t spare_hook7;
};
注意:在configure之后生成的文件 objs/ngx_modules.c 中包含了模块的编译顺序。
1、解析HTTP配置的流程
首先要理解 ngx_conf_parse() 的递归解析流程;
nginx在解析nginx.conf的时候,没读取一行配置项,就执行该配置项的解析回调(handler);
原文:http://www.cnblogs.com/chenny7/p/3544352.html