nginx的ngx_http_sub_module模块,能够用于修改网站响应内容中的字符串,如过滤敏感词。第三方模块ngx_http_substitutions_filter_module,弥补了ngx_http_sub_module的不足,能够采用正则表达式替换。html
part 一、安装ngx_http_sub_module
nginx默认是不安装ngx_http_sub_module模块的,直接应用sub_filter指令将报错nginx
nginx: [emerg] unknown directive "sub_filter" in /nginx-test/conf/nginx.conf:49
所以须要在编译过程当中添加 --with-http_sub_module 参数git
# 编译
./configure --prefix=/nginx-sub --with-http_sub_module
# 安装
make install
part 二、sub模块替换文本
官网文档说明,ngx_http_sub_module包括四个命令:github
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指令是执行一次,仍是重复执行,默认是只执行一次tcp
sub_filter_types mime-type
...; default: text/html 指定类型的MINE TYPE才有效网站
下面以替换路飞为例:spa
sub.html原始文本为:code
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 三、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; }