nginx sub模塊替換文本

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; }

 

 

相關文章
相關標籤/搜索