一个请求可以被任意个HTTP模块处理

  在普通HTTP模块处理请求完毕并调用ngx_http_send_header()发送HTTP头部或调用ngx_http_output_filter()发送HTTP包体时,才会由这两个方法一次调用所有的HTTP过滤模块来处理这个请求。HTTP过滤模块仅处理服务器发送到客户端的响应,而不处理客户端发往服务器的HTTP请求。

  多个过滤模块的顺序的形成以及Nginx自带的过滤模块请参考原书。

 

二、编写一个HTTP过滤模块

   以向返回给用户的文本格式响应包体前加一段字符串"[my filter prefix]"为例,展示如何编写一个HTTP过滤模块。源代码来自于《深入理解Nginx》。

1.config文件的编写

  与前几篇博文的HTTP模块不同,HTTP过滤模块需要HTTP_FILTER_MODULES一项以把所有过滤模块一同编译,因此config写作:

ngx_addon_name=ngx_http_myfilter_module
HTTP_FILTER_MODULES="$HTTP_FILTER_MODULES ngx_http_myfilter_module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_myfilter_module.c"

  进行configure时,--add-module=PATH是一样的。

 

2.编写模块基本内容:模块定义、配置项处理

  由于需要在nginx.conf中加入一项flag类型的add_fix来控制这个过滤模块的使用与否,与这个配置项处理相关的ngx_http_myfilter_create_conf()、ngx_http_myfilter_merge_conf()、ngx_http_mytest_commands[]需要对应地进行处理。

typedef struct {
    ngx_flag_t enable;
} ngx_http_myfilter_conf_t;

typedef struct {
    ngx_int_t add_prefix;
} ngx_http_myfilter_ctx_t;

 

static void* ngx_http_myfilter_create_conf(ngx_conf_t *cf)
{
    ngx_http_myfilter_conf_t *mycf;
    mycf = (ngx_http_myfilter_conf_t *)ngx_pcalloc(cf->pool,sizeof(ngx_http_myfilter_conf_t));
    if(mycf == NULL) {
        return NULL;
    }
    mycf->enable = NGX_CONF_UNSET;
    return mycf;
}
ngx_http_myfilter_create_conf()

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2021-05-17
  • 2021-10-06
  • 2021-06-10
  • 2022-12-23
  • 2021-07-05
  • 2021-08-19
猜你喜欢
  • 2022-01-22
  • 2021-07-14
  • 2022-02-22
  • 2021-10-05
  • 2021-12-28
相关资源
相似解决方案