全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

模块配置指令解析

Nginx 模块通过指令数组注册配置指令,解析流程由核心框架驱动,模块只需提供解析回调。

指令注册机制

ngx_command_t 结构

C
typedef struct ngx_command_s {
    ngx_str_t             name;      // 指令名称
    ngx_uint_t            type;      // 指令类型与参数约束
    char               *(*set)(...); // 解析回调函数
    ngx_uint_t            conf;      // 配置偏移位置
    ngx_uint_t            offset;    // 配置结构体字段偏移
    void                 *post;      // 附加数据
} ngx_command_t;

type 标志位组合

标志位说明
NGX_DIRECT_CONF直接配置,不创建子结构体
NGX_MAIN_CONFmain 级别配置
NGX_EVENT_CONFevents 块内有效
NGX_HTTP_CONFhttp 块内有效
NGX_HTTP_SRV_CONFserver 块内有效
NGX_HTTP_LOC_CONFlocation 块内有效
NGX_CONF_TAKE1固定 1 个参数
NGX_CONF_TAKE2固定 2 个参数
NGX_CONF_FLAG布尔标志 on/off

解析回调函数

标准解析函数

C
// 字符串类型指令
{ ngx_string("my_directive"),
  NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1,
  ngx_conf_set_str_slot,
  NGX_HTTP_MAIN_CONF_OFFSET,
  offsetof(ngx_http_my_conf_t, my_str),
  NULL }

// 数值类型指令
{ ngx_string("my_number"),
  NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
  ngx_conf_set_num_slot,
  NGX_HTTP_LOC_CONF_OFFSET,
  offsetof(ngx_http_my_conf_t, my_num),
  NULL }

// 布尔标志
{ ngx_string("my_flag"),
  NGX_HTTP_SRV_CONF|NGX_CONF_FLAG,
  ngx_conf_set_flag_slot,
  NGX_HTTP_SRV_CONF_OFFSET,
  offsetof(ngx_http_my_conf_t, my_flag),
  NULL }

自定义解析函数

C
static char *
ngx_http_my_custom(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_my_conf_t *mcf = conf;
    ngx_str_t          *value = cf->args->elts;

    if (cf->args->nelts != 3) {
        return "invalid number of arguments";
    }

    mcf->param1 = value[1];
    mcf->param2 = value[2];

    return NGX_CONF_OK;
}

自定义解析函数必须返回 NGX_CONF_OK 表示成功,返回字符串表示错误信息。

配置结构体与合并

三级配置结构

C
typedef struct {
    ngx_str_t  upstream;
    ngx_int_t  timeout;
    ngx_flag_t enable;
} ngx_http_my_conf_t;

配置合并机制

C
static char *
ngx_http_my_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
    ngx_http_my_conf_t *prev = parent;
    ngx_http_my_conf_t *conf = child;

    ngx_conf_merge_str_value(conf->upstream, prev->upstream, "default");
    ngx_conf_merge_value(conf->timeout, prev->timeout, 30000);
    ngx_conf_merge_flag_value(conf->enable, prev->enable, 1);

    return NGX_CONF_OK;
}

子作用域未显式配置时,自动继承父作用域的值,避免配置断裂。

配置创建回调

create_conf 与 init_conf

C
static void *
ngx_http_my_create_main_conf(ngx_conf_t *cf)
{
    ngx_http_my_conf_t  *conf;

    conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_my_conf_t));
    if (conf == NULL) {
        return NULL;
    }

    conf->timeout = NGX_CONF_UNSET;
    conf->enable  = NGX_CONF_UNSET;

    return conf;
}

配置结构体使用 ngx_pcalloc 分配,初始值设为 NGX_CONF_UNSET,合并阶段处理默认值。

要点总结

  • 指令通过 ngx_command_t 数组注册,type 定义作用域与参数约束
  • 解析回调可使用内置函数(ngx_conf_set_str_slot 等)或自定义函数
  • 配置结构体分 main/srv/loc 三级,子级可覆盖或继承父级配置
  • create_conf 分配内存并标记未设置字段,merge_conf 处理继承与默认值
  • 解析失败返回错误字符串,成功返回 NGX_CONF_OK

📝 发现内容有误?点击此处直接编辑

← 上一篇 模块编译与集成
下一篇 → 请求处理与钩子函数
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库