您的位置:首页 > 运维架构 > Nginx

nginx源码分析-过滤模块

2012-09-06 14:49 363 查看
auth:农夫-Ben
email:szjava#126.com(请把#换成@)
blog:http://blog.csdn.net/zll_liang

本文介绍nginx的过滤模块,主要为过滤模块的处理流程。
nginx各过滤模块的定义:
ngx_http_not_modified_filter_module
默认打开,如果请求的if-modified-since等于回复的last-modified间值,说明回复没有变化,清空所有回复的内容,返回304。

ngx_http_range_body_filter_module
默认打开,只是响应体过滤函数,支持range功能,如果请求包含range请求,那就只发送range请求的一段内容。

ngx_http_copy_filter_module
始终打开,只是响应体过滤函数, 主要工作是把文件中内容读到内存中,以便进行处理。

ngx_http_headers_filter_module
始终打开,可以设置expire和Cache-control头,可以添加任意名称的头

ngx_http_userid_filter_module
默认关闭,可以添加统计用的识别用户的cookie。

ngx_http_charset_filter_module
默认关闭,可以添加charset,也可以将内容从一种字符集转换到另外一种字符集,不支持多字节字符集。

ngx_http_ssi_filter_module
默认关闭,过滤SSI请求,可以发起子请求,去获取include进来的文件

ngx_http_postpone_filter_module
始终打开,用来将子请求和主请求的输出链合并

ngx_http_gzip_filter_module
默认关闭,支持流式的压缩内容

ngx_http_range_header_filter_module
默认打开,只是响应头过滤函数,用来解析range头,并产生range响应的头。

ngx_http_chunked_filter_module
默认打开,对于HTTP/1.1和缺少content-length的回复自动打开

ngx_http_header_filter_module
始终打开,用来将所有header组成一个完整的HTTP头。

ngx_http_write_filter_module
始终打开,将输出链拷贝到r->out中,然后输出内容 为最后一个filter

过滤模块执行顺序:
它的顺序在编译的时候就决定了。控制编译的脚本位于auto/modules中,当你编译完nginx以后,可以在objs目录下面看到一个ngx_modules.c的文件。打开这个文件:
ngx_module_t *ngx_modules[] = {
....
&ngx_http_write_filter_module,
&ngx_http_header_filter_module,
&ngx_http_chunked_filter_module,
&ngx_http_range_header_filter_module,
&ngx_http_gzip_filter_module,
&ngx_http_postpone_filter_module,
&ngx_http_ssi_filter_module,
&ngx_http_charset_filter_module,
&ngx_http_userid_filter_module,
&ngx_http_headers_filter_module,
&ngx_http_copy_filter_module,
&ngx_http_range_body_filter_module,
&ngx_http_not_modified_filter_module,
NULL
};


加载顺序是倒过来了。呵呵 ,先执行ngx_http_not_modified_filter_module,最后执行:ngx_http_write_filter_module

那它们是怎么样连接起来走顺序的呢?它采用了一种很隐晦的方法,通过局部的全局变量。比如,在每个filter模块,很可能看到如下代码:

ngx_http_next_header_filter = ngx_http_top_header_filter;
ngx_http_top_header_filter = ngx_http_image_header_filter;

ngx_http_next_body_filter = ngx_http_top_body_filter;
ngx_http_top_body_filter = ngx_http_image_body_filter;


ngx_http_top_header_filter是一个全局变量。当编译进一个filter模块的时候,就被赋值为当前filter模块的处理函数。而ngx_http_next_header_filter是一个该模块的模块全局变量,它保存了编译前上一个filter模块的处理函数。所以整体看来,就像用全局变量组成的一条单向链表。

每个模块想执行下一个过滤函数,只要调用一下ngx_http_next_header_filter这个局部变量。而整个过滤模块链的入口,只要调用ngx_http_top_header_filter这个全局变量就可以了。ngx_http_top_body_filter也一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: