天天看點

nginx中http_sub_module子產品(替換網站響應内容)

ngx_http_sub_module子產品是一個過濾器,它修改網站響應内容中的字元串,比如你想把響應内容中的‘ttlsa’全部替換成‘運維生存時間’,這個子產品已經内置在nginx中,但是預設未安裝,需要安裝需要加上配置參數:–with-http_sub_module

1. 安裝nginx

# wget http://nginx.org/download/nginx-1.4.2.tar.gz  

# tar -xzvf nginx-1.4.2.tar.gz  

# cd nginx-1.4.2  

#  --prefix=/usr/local/nginx-1.4.2 --with-http_stub_status_module --with-http_sub_module  

# make  

# make install 

如果你已經安裝了nginx,隻需要額外追加這個子產品,請看如何安裝nginx第三方子產品

2. 指令(Directives)

文法:     sub_filter string replacement;

預設值:     —

配置段:     http, server, location

設定需要使用說明字元串替換說明字元串.string是要被替換的字元串,replacement是新的字元串,它裡面可以帶變量。

文法:     sub_filter_last_modified on | off;

預設值:  sub_filter_last_modified off;

這個指令在nginx 1.5.1中添加,我這個版本沒有,可以忽略掉.

Allows preserving the “Last-Modified” header field from the original response during replacement to facilitate response caching.

By default, the header field is removed as contents of the response are modified during processing.

文法: sub_filter_once on | off;

預設值: sub_filter_once on;

配置段: http, server, location

字元串替換一次還是多次替換,預設替換一次,例如你要替換響應内容中的ttlsa為運維生存時間,如果有多個ttlsa出現,那麼隻會替換第一個,如果off,那麼所有的ttlsa都會 被替換

文法: sub_filter_types mime-type …;

預設值: sub_filter_types text/html;

指定需要被替換的MIME類型,預設為“text/html”,如果制定為*,那麼所有的

3. nginx替換字元串執行個體

3.1 配置

server {  

    listen       80;  

    server_name  www.ttlsa.com;     

    root /data/site/www.ttlsa.com;      

    location / {  

        sub_filter  ttlsa '運維生存時間';  

        sub_filter_types text/html;  

        sub_filter_once on;  

    }  

3.2 測試

内容如下

# cat /data/site/www.ttlsa.com/2013/10/20131001_sub1.html   

welcome to tTlsa!  

TTLSA TEAM! 

通路結果

# curl www.ttlsa.com/2013/10/20131001_sub1.html             

welcome to 運維生存時間!  

我們可以看到它替換是不區分大小寫的,而且ttlsa隻被替換了一次。我把sub_filter_once on改成off試試。

location / {  

    sub_filter  ttlsa '運維生存時間';  

    sub_filter_once off;  

接着測試

# curl www.ttlsa.com/2013/10/20131001_sub1.html              

運維生存時間 TEAM! 

我們可以看到ttlsa都被替換掉了.

例如你想在</head>後追加一段js,配置如下:

location / { 

    sub_filter      </head> '</head><script language="javascript" src="$script"></script>';  

    sub_filter_once on;  

這邊我就不再做測試了,大家可以測試一下.

4. 結束語

這個nginx替換響應内容的子產品安裝使用尤為簡單,應用的地方相對較少,在nginx中也是一個可選子產品。假如站點出現什麼敏感字,想修改很耗時間,不妨試試這個子產品.或者想臨時在站點中加上一個通用js或者css之類的檔案,也可以使用這個子產品.至于要在哪裡,大家看看自己的需求.

本文轉自  亮公子  51CTO部落格,原文連結:http://blog.51cto.com/iyull/1864380

繼續閱讀