nginx sub模块替换文本
young / / / 阅读量

介绍

nginx的ngx_http_sub_module模块,可以用于修改网站响应内容中的字符串,如过滤敏感词。

第三方模块ngx_http_substitutions_filter_module,弥补了ngx_http_sub_module的不足,可以采用正则表达式替换。(此处不讲如有需要自行查阅相关文档)

安装

nginx自带ngx_http_sub_module模块,但是默认不安装ngx_http_sub_module模块的,因此需要在编译过程中添加 –with-http_sub_module 参数即可

用法

ngx_http_sub_module包括四个命令:

# 将字符串string修改成replacement,不区分大小写,传入文本是上一次处理后的文本
sub_filter string replacement;                 

# 是否阻止response header中写入Last-Modified,防止缓存,默认是off,即防止缓存
sub_filter_last_modified on | off;    

# sub_filter指令是执行一次,还是重复执行,默认是只执行一次
sub_filter_once on | off;    

# 指定类型的MINE TYPE才有效 默认有 text/html
sub_filter_types mime-type ...;

示例

以替换localhost为例:

原始文本为:

test1 Localhost:8080
test2 Localhost:8081
test3 Localhost:8082

只修改一次

location /sub {
    sub_filter 'localhost' '192.168.2.1';
}

替换结果

test1 192.168.2.1:8080
test2 Localhost:8081
test3 Localhost:8082

发现不区分大小写的把localhost替换为了192.168.2.1 ,只替换了第一行

重复执行修改

location /sub {
    sub_filter 'localhost' '192.168.2.1';
    sub_filter_once off;
}

替换结果

test1 192.168.2.1:8080
test2 192.168.2.1:8081
test3 192.168.2.1:8082

这次把所有行Localhost都替换成192.168.2.1了

支付宝捐赠
请使用支付宝扫一扫进行捐赠
微信捐赠
请使用微信扫一扫进行赞赏
有 0 篇文章