1.指令(Directives)
语法:
sub_filter string replacement;
默认值: —
配置段: http, server, location
设置需要使用说明字符串替换说明字符串.string是要被替换的字符串,replacement是新的字符串,它里面可以带变量。
语法:
sub_filter_last_modified on | off;
默认值: sub_filter_last_modified off;
配置段: http, server, location
这个指令在nginx 1.5.1中添加,我这个版本没有,可以忽略掉.
Allows preserving the “Last-Modified” header field from the original response during replacement to facilitate response caching.
By default, the header field is removed as contents of the response are modified during processing.
语法:
sub_filter_once on | off;
默认值: sub_filter_once on;
配置段: http, server, location
字符串替换一次还是多次替换,默认替换一次,例如你要替换响应内容中的jb51为易采站长站,如果有多个jb51出现,那么只会替换第一个,如果off,那么所有的jb51都会 被替换
语法:
sub_filter_types mime-type ...;
默认值: sub_filter_types text/html;
配置段: http, server, location
指定需要被替换的MIME类型,默认为“text/html”,如果制定为*,那么所有的
2. nginx替换字符串实例
2.1 配置
server {
listen 80;
server_name www.jb51.net;
root /data/site/www.jb51.net;
location / {
sub_filter jb51 '易采站长站';
sub_filter_types text/html;
sub_filter_once on;
}
}
2.2 测试
内容如下
# cat /data/site/www.jb51.net/2013/10/20131001_sub1.html
welcome to jb51! jb51 TEAM!
访问结果
# curl www.jb51.net/2013/10/20131001_sub1.html
welcome to 易采站长站! jb51 TEAM!
我们可以看到它替换是不区分大小写的,而且jb51只被替换了一次。我把sub_filter_once on改成off试试。
location / {
sub_filter jb51 '易采站长站';
sub_filter_once off;
}
接着测试
# curl www.jb51.net/2013/10/20131001_sub1.html
welcome to 易采站长站! 易采站长站 TEAM!
我们可以看到jb51都被替换掉了.
例如你想在</head>后追加一段js,配置如下:
location / {
sub_filter </head> '</head><script language="javascript" src="$script"></script>';
sub_filter_once on;
}
这边我就不再做测试了,大家可以测试一下.








