Nginx 模块开发

初级教程

http://www.evanmiller.org/nginx-modules-guide.html

 

高级教程

http://www.evanmiller.org/nginx-modules-guide-advanced.html

 

假设要作广告过滤,通过URL HOST 来过滤一些请求的简单样例, 字符串处理有BUG

 

#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include <ngx_string.h>


static ngx_int_t ngx_http_adfilter_init(ngx_conf_t *cf);
static ngx_http_output_body_filter_pt    ngx_http_next_body_filter;

static ngx_http_module_t  ngx_http_adfilter_module_ctx = {
    NULL,                                   /* preconfiguration */
    ngx_http_adfilter_init,     /* postconfiguration */

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

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

    NULL,                                  /* create location configuration */
    NULL,                                  /* merge location configuration */
};


ngx_module_t  ngx_http_adfilter_module = {
    NGX_MODULE_V1,
    &ngx_http_adfilter_module_ctx,     /* module context */
    NULL,                                  /* 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
};


ngx_int_t
ngx_http_adfilter(ngx_http_request_t *r, ngx_chain_t *in)
{
    ngx_connection_t          *c;
 int len = 0;
    c = r->connection;
    if (c->error) {
       return NGX_ERROR;
    }   
 


 len = r->host_end - r->host_start + 1;
 char * adhost = "i0.sinaimg.cn";
 u_char * str = (u_char*)ngx_alloc( sizeof(u_char) * len , c->log);
 ngx_memcpy(str, r->host_start, len -1 );
 str[len-1] = '\0';

  ngx_log_debug1(NGX_LOG_INFO, c->log,NGX_LOG_INFO, "Host is: [%s]", str);
 if(0 == strncmp(adhost, (char*)str, strlen(adhost)))
 {
  ngx_log_debug1(NGX_LOG_INFO, c->log,NGX_LOG_INFO, "!!! Skip Host: %s", str);
  return NGX_OK;
 }

 ngx_calloc(sizeof(str), c->log);

 return ngx_http_next_body_filter(r,in);
}


ngx_int_t ngx_http_adfilter_init(ngx_conf_t *cf)
{
 ngx_http_next_body_filter = ngx_http_top_body_filter;
    ngx_http_top_body_filter = ngx_http_adfilter;
    return NGX_OK;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值