nginx module

90 阅读1分钟

nginx模块类型

  • core module
  • event
    • ngx_epoll_module
    • ngx_select_module
  • mail
    • ngx_mail_core_module
    • ngx_mail_pop3_module
    • ngx_mail_smtp_module
    • ...
  • misc
  • os
  • stream
    • ngx_stream_xxx_module
  • http
    • ngx_http_core_module
    • ngx_http_xxx_module

一个nginx模块的定义

以http access模块为例:

ngx_module_t  ngx_http_access_module = {
    NGX_MODULE_V1,
    &ngx_http_access_module_ctx,           /* module context */
    ngx_http_access_commands,              /* module directives */
    NGX_HTTP_MODULE,                       /* module type */
    NULL,                                  /* init master */
    NULL,                                  /* init module */
    NULL,                                  /* init process */
    NULL,                                  /* init thread */
    NULL,                                  /* exit thread */
    NULL,                                  /* exit process */
    NULL,                                  /* exit master */
    NGX_MODULE_V1_PADDING
};

常用的只有3个属性,一个是module context, 一个是配置命令定义,一个是模块类型。

先看module context

static ngx_http_module_t  ngx_http_access_module_ctx = {
    NULL,                                  /* preconfiguration */
    ngx_http_access_init,                  /* postconfiguration */

    NULL,                                  /* create main configuration */
    NULL,                                  /* init main configuration */

    NULL,                                  /* create server configuration */
    NULL,                                  /* merge server configuration */

    ngx_http_access_create_loc_conf,       /* create location configuration */
    ngx_http_access_merge_loc_conf         /* merge location configuration */
};

可以看到module context是对配置的处理,这里有3个函数,一个是postconfiguration,一个是create configuration,一个是merge configuration,因为可以配置多个location块,所以需要merge。

再看配置命令定义

static ngx_command_t  ngx_http_access_commands[] = {

    { ngx_string("allow"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF
                        |NGX_CONF_TAKE1,
      ngx_http_access_rule,
      NGX_HTTP_LOC_CONF_OFFSET,
      0,
      NULL },

    { ngx_string("deny"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LMT_CONF
                        |NGX_CONF_TAKE1,
      ngx_http_access_rule,
      NGX_HTTP_LOC_CONF_OFFSET,
      0,
      NULL },

      ngx_null_command
};

这些都是固定格式,熟悉就可以了。 每个命令关键字对应一个函数。有点类似tcl语言。

最后模块类型

模块类型就是开头的图标显示的,最常见的就是http mdoule。