Nginx配置文件处理过程

Linux大全评论688 views阅读模式

本文总结这段时间阅读Nginx处理配置文件的代码。其中很多参考网上的资料,主要是淘宝的那一份。现在,算是有个大体的了解了。先记录下来,以后有加深的认识,再继续补上。加油!

1. 配置文件处理的主要步骤和过程

nginx.c文件main函数

    ngx_max_module = 0;
    for (i = 0; ngx_modules[i]; i++) {
        ngx_modules[i]->index = ngx_max_module++;
    }

初始化所有模块的索引顺序ngx_modules[i]->index,和ngx_max_module。

调用ngx_init_cycle(&init_cycle)。

ngx_init_cycle

1.创建conf_ctx存放所有配置结构体

cycle->conf_ctx = ngx_pcalloc(pool, ngx_max_module * sizeof(void *));

2.NGX_CORE_MODULE模块配置结构体初始化,并存放于cycle->conf_ctx数组中。

    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

        module = ngx_modules[i]->ctx;

        if (module->create_conf) {
            rv = module->create_conf(cycle); 
            if (rv == NULL) {
                ngx_destroy_pool(pool);
                return NULL;
            }
            cycle->conf_ctx[ngx_modules[i]->index] = rv;
        }
    }

3.调用ngx_conf_param()和ngx_conf_parse()解析配置文件。具体看下一个章节。

conf.ctx = cycle->conf_ctx;
if (ngx_conf_param(&conf) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }
    if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

4.调用NGX_CORE_MODULE模块的init_conf函数。

  for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

        module = ngx_modules[i]->ctx;

        if (module->init_conf) {
            if (module->init_conf(cycle, cycle->conf_ctx[ngx_modules[i]->index])
                == NGX_CONF_ERROR)
            {
                environ = senv;
                ngx_destroy_cycle_pools(&conf);
                return NULL;
            }
        }
    }

ngx_conf_parse()函数

截取主要代码部分。读取一个配置指令,交给ngx_conf_handler进行处理,如果返回NGX_ERROR则出错结束。

企鹅博客
  • 本文由 发表于 2019年9月27日 01:29:16
  • 转载请务必保留本文链接:https://www.qieseo.com/158059.html

发表评论