初级教程
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;
}