有时我们需要在nginx配置给每个响应中加入指定代码,比如统计代码,或者公共信息,我们只需要使用nginx的sub_filter就可以完成。
sub_filter功能是ngx_http_sub_module模块实现的,这个模块并不是nginx默认就会安装的,需要你在编译的时候使用–with-http_sub_module参数编译。
ngx_http_sub_module的使用很简单,共有4个参数:
syntax: sub_filter string replacement;
default: —
context: http, server, location
这个参数指明了用replacement替换string匹配的字符串
syntax: sub_filter_last_modified on | off;
default: sub_filter_last_modified off;
context: http, server, location
This directive appeared in version 1.5.1.
这个参数指明了替换的时候修改响应头部的”Last-Modified”,默认是关闭的。
syntax: sub_filter_once on | off;
default: sub_filter_once on;
context: http, server, location
这个参数指明了是匹配一次还是匹配多次,默认是匹配多次。
syntax: sub_filter_types mime-type …;
default: sub_filter_types text/html;
context: http, server, location
这个参数指明了哪种类型的响应允许被替换,默认是text/html,*代表所有MIME type。
反映到我们添加统计代码的需求上,我们只需要配置sub_filter参数即可。
sub_filter