nginx替換響應內容


  因為想要將非業務域名內嵌到微信小程序中,所以用到了nginx的反向代理功能來替換域名實現盜站(緣起:http://www.cnblogs.com/kenwar/p/8288882.html),但是替換域名后問題來了,因為XmlHttpRequest同源策略:“禁止向不同源的地址發起HTTP請求” 所以光替換域名還是不夠,還需要替換響應內容里的一些ajax請求,這就涉及到了nginx的響應內容替換功能。

  一、簡單替換模塊 ngx_http_sub_module:

    (1)介紹:

      ngx_http_sub_module模塊是一個過濾器,它修改網站響應內容中的字符串。這個模塊已經內置在nginx中,但是默認未安裝,需要安裝需要加上配置參數:--with-http_sub_module 如果已經安裝nginx,只需要再添加這個模塊就可以了。

    (2)常用指令:

      2.1 sub_filter指令: sub_filter string(原字符串) replacement(用於替換的字符串);

        用於設置需要使用說明字符串替換說明字符串.string是要被替換的字符串,replacement是 新的字符串,它里面可以帶變量。

      2.2 sub_filter_last_modified指令: sub_filter_last_modified on | off;

        用於設置網頁內替換后是否修改 可在nginx.conf的 http, server, location三個位置配置使 用,默認值是off;

      2.3 sub_filter_once指令:sub_filter_once on | off;

        用於設置字符串替換次數,默認只替換一次。如果是on,默認只替換第一次匹配到的到字 符,如果是off,那么所有匹配到的字符都會被替換;

      2.4 sub_filter_types指令:sub_filter_types * 

        用於指定需要被替換的MIME類型,默認為“text/html”,如果制定為*,那么所有的;

    (3)說明:

      3.1以上指令可在nginx.conf的http, server, location三個位置配置使用;

      3.2此模塊替換不區分大小寫;

      3.3支持中文替換;

    (4)示例:     

location ^~/im/ {
    proxy_pass http://p.qiao.baidu.com;
    add_header Access-Control-Allow-Origin *;
    sub_filter 'http://p.qiao.baidu.com' 'https://www.demo.com';##將響應內容中的域名替換成本站域名
    sub_filter_once off;####所有匹配到的都替換
}

    (5)總結:

       使用ngx_http_sub_module模塊好處是nginx內置該模塊使用方便,不足之處在於該模塊不支持正則替換,靈活性不夠

  二、支持正則匹配替換的第三方模塊ngx_http_substitutions_filter_module:

    (1)下載地址:https://github.com/yaoweibin/ngx_http_substitutions_filter_module/archive/master.zip

    (2)解壓縮,平滑升級nginx(升級方式可參考前一篇文章平滑添加ssl模塊:http://www.cnblogs.com/kenwar/p/8295907.html (添加參數--add-module=/模塊解壓后文件路徑))

    (3)使用說明:

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;
    subs_filter http://$host https://$host;
}
從github給出的使用示例來看,這個模塊涉及2個指令:
* subs_filter_types
subs_filter_types 語法: subs_filter_types mime-type [mime-types]
默認: subs_filter_types text/html
適用: http, server, location
subs_filter_types 是用來指定替換文件類型的 默認僅僅替換text/html類型的文件。

* subs_filter
subs_filter 語法: subs_filter source_str destination_str [gior]
默認: none
適用: http,server,location
subs_filter 是用來替換文本的,可以使用正則
g(默認):替換匹配項。
i  :區分大小寫的匹配
o : 只匹配發現的第一個。
r  : 正則匹配。

    (4)案例分享:

        替換響應內容中的某個js,因為js版本不固定,路徑是變動的,所以用到正則

location ^~/f/ {
         proxy_pass http://xxx.xxxx.com;
         add_header Access-Control-Allow-Origin *;
     subs_filter 'https://cdn.jinshuju.net/assets/published_forms/mobile/application-(.*?(\.js){1})' 'https://www.demo.com/comm/js/jinshujujsforsmallproject.js' ir ;
 }

    (5)說明:

       在使用正則模式時,不能使用nginx內置變量,比如:$host,否則會出現如下報錯:
        nginx: [emerg] match part cannot contain variable during regex mode in *


免責聲明!

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



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