nginx ngx_http_sub_module使用


ngx_http_sub_module模塊是一個過濾器,它修改網站響應內容中的字符串,比如你想把響應內容中的‘iuwai’全部替換成‘aaaaa‘,這個模塊已經內置在nginx中,但是默認未安裝,需要安裝需要加上配置參數:–with-http_sub_module

因為公司對外提供的接口(xml)格式中需要將里面的二級域名替換下,從代碼方面確實可以修改,但是更麻煩,有了這個module替換字符串就方便多了:

1.先查看是否有這個module:

./sbin/nginx -V

 

如果沒有則需要重新編譯安裝:

./configure--prefix=/data01/nginx --with-pcre=/data01/pcre-8.35 --without-http_gzip_module --with-http_sub_module

make && make install

安裝完畢需要修改nginx.conf

location / {
            root   html;
            index  index.html index.htm;
            sub_filter iuwai aaaaaa;
            sub_filter_types *;
            sub_filter_once off;
        }

官方示例:

location / {
    sub_filter      </head>
        '</head><script language="javascript" src="$script"></script>';
    sub_filter_once on;
}

 

然后重啟./sbin/nginx -s reload

ok!

以上方法只能做一次替換,不能有多個字符串的不同替換,HttpSubsModule這個模塊就可以提供多個替換方式:

首先需要安裝這個模塊,

模塊下載地址:

git clone git://github.com/yaoweibin/ngx_http_substitutions_filter_module.git

重新編譯:

./configure --prefix=/data01/nginx --with-pcre=/data01/pcre-8.35 --without-http_gzip_module --with-http_sub_module --add-module=/data01/ngx_http_substitutions_filter_module/
make && make install

 官方給的實例:

location / {
 
    subs_filter_types text/html text/css text/xml;
    subs_filter st(\d*).example.com $1.example.com ir;
    subs_filter a.example.com s.example.com;
 
}

 我的配置:

location / {
            root   html;
            index  index.html index.htm;
            subs_filter iuwai aaaaaa;
            subs_filter baidu bbbbb;
            subs_filter_types *;
            #sub_filter_once off;
        }

 OK,大功告成,返回的頁面內容隨意修改,很神奇吧!

結束語:

另外還可以指定只匹配一個、是否區分大小寫、正則匹配替換。

此方式有以下功能:

1.如官方示例,需要添加js文件、或css樣式文件

2.替換頁面中的敏感字


免責聲明!

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



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