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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM