25.Nginx之HTTP入口

来源:互联网 发布:免费淘宝代理童装 编辑:程序博客网 时间:2024/04/28 21:00

学习了前面的一些代码,我们大概知道了Nginx的进程模型与事件处理模型,但是Nginx是著名的HTTP服务器,而我们目前好像并未学习到任何与HTTP相关的代码,那么Nginx究竟是怎么使用HTTP的各个模块的呢?


前面我们学习了Nginx的启动流程之ngx_init_cycle这个环节,而里面涉及到配置文件解析的内容,代码如下所示。从这个代码片段,我们可以发现: Nginx的配置文件解析是从NGX_CORE_MODULE类型的模块开始的。

    conf.ctx = cycle->conf_ctx;    conf.cycle = cycle;    conf.pool = pool;    conf.log = log;    conf.module_type = NGX_CORE_MODULE;    conf.cmd_type = NGX_MAIN_CONF;    if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) {        ngx_destroy_pool(pool);        return NULL;    }


然后我们从ngx_modules可以找到以下和HTTP有关的模块:

    &ngx_http_module,    &ngx_http_core_module,    &ngx_http_log_module,    &ngx_http_static_module,    &ngx_http_index_module,    &ngx_http_access_module,    &ngx_http_rewrite_module,    &ngx_http_proxy_module,    &ngx_http_write_filter_module,    &ngx_http_header_filter_module,    &ngx_http_chunked_filter_module,    &ngx_http_range_header_filter_module,    &ngx_http_gzip_filter_module,    &ngx_http_charset_filter_module,    &ngx_http_userid_filter_module,    &ngx_http_headers_filter_module,    &ngx_http_copy_filter_module,    &ngx_http_range_body_filter_module,    &ngx_http_not_modified_filter_module,
我们找到ngx_http_module这个模块的定义如下,很巧的是,该模块的类型就是NGX_CORE_MODULE。从下面的代码片段可以发现,当解析到以http开始的配置块时,会调用ngx_http_block来对配置块内的内容进行进一步解析,而ngx_http_block正是我们要找的答案。

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};    static ngx_core_module_t  ngx_http_module_ctx = {    ngx_string("http"),    NULL,    NULL};  ngx_module_t  ngx_http_module = {    NGX_MODULE,    &ngx_http_module_ctx,                  /* module context */    ngx_http_commands,                     /* module directives */    NGX_CORE_MODULE,                       /* module type */    NULL,                                  /* init module */    NULL                                   /* init child */};
从上面我们可以得出一个结论: 当我们扩展Nginx的应用模块时,譬如让Nginx处理mail,那么我们首先需要定义一个NGX_CORE_MODULE类型的mail模块,而该模块的指令集需要包含mail,我们也需要为该指令注册一个回调函数用作全部mail模块的入口。