nginx sub模块替换文本

nginx的ngx_http_sub_module模块,可以用于修改网站响应内容中的字符串,如过滤敏感词。第三方模块ngx_http_substitutions_filter_module,弥补了ngx_http_sub_module的不足,可以采用正则表达式替换。

part 1、安装ngx_http_sub_module

nginx默认是不安装ngx_http_sub_module模块的,直接应用sub_filter指令将报错

nginx: [emerg] unknown directive "sub_filter" in /nginx-test/conf/nginx.conf:49

因此需要在编译过程中添加 --with-http_sub_module 参数

# 编译
./configure --prefix=/nginx-sub --with-http_sub_module
# 安装
make install

part 2、sub模块替换文本

官网文档说明,ngx_http_sub_module包括四个命令:

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

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

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

sub_filter_types mime-type ...;      default: text/html    指定类型的MINE TYPE才有效

下面以替换路飞为例:

sub.html原始文本为:

1)修改一次

location /sub {
    sub_filter 'luffy' '路飞';
}

发现不区分大小写的把Luffy替换为了路飞,而第三行的luffy不变

2)重复执行修改

location /sub {
    sub_filter 'luffy' '路飞';
  sub_filter_once off; }

 

这次把Luffy和luffy都替换成路飞了

 

备注:开放80端口命令

# 开启端口
# --zone #作用域
# --add-port=80/tcp #添加端口,格式为:端口/通讯协议
# --permanent #永久生效,没有此参数重启后失效
firewall-cmd --zone=public --add-port=80/tcp --permanent
# 重启防火墙
firewall-cmd --reload

 part 3、subs_filter多个替换

ngx_http_substitutions_filter_module是一个第三方模块,它可以多次替换或者正则替换网站响应内容,需要通过--add-module参数编译添加

首先需要下载,地址是:https://github.com/yaoweibin/ngx_http_substitutions_filter_module 

下载之后,我放在了与nginx源码平级的目录下

# 编译
./configure --prefix=/nginx-sub --with-http_sub_module --add-module=../ngx_http_substitutions_filter_module-master
# 安装
make install 
subs_filter source_str destination_str [gior]   default:g    默认是全局匹配,大小写敏感

使用subs_filter指令

location /sub {
    subs_filter 'luffy' '路飞';
}

location /sub {
    subs_filter 'luffy' '路飞' i;
}

 

使用正则表达式:

location /sub {
    subs_filter luffy|鲁夫 路飞 ir;
}

 

 

 

posted @ 2018-02-05 15:11  zhang90030  阅读(11680)  评论(0编辑  收藏  举报