Nginx的代理功能太完善了,我們看看proxy_redirect參數的作用。
案例說明:
要做一個html.md5.cn的功能變數名稱處理很多網站的html內容,當然是後端的伺服器了,目錄分析

html.zcom.com/img.md5.cn/
html.zcom.com/css.md5.cn/

訪問的功能變數名稱是該目錄下的功能變數名稱,那前端nginx的配置應該類似這樣:

server {
  server_name img.md5.cn;
  location / {
    rewrite ^(.*) /$http_host$1 break;
    proxy_set_header Host html.md5.cn;
    proxy_pass http://cache-89;
  }
}

 

但這樣訪問目錄時如果沒有以“/”結尾,則伺服器會返回301redirect:

[root@aslibra ~]# curl -I http://img.md5.cn/www
HTTP/1.1 301 Moved Permanently
Server: nginx/0.7.59
Date: Tue, 21 Jul 2009 15:28:58 GMT
Connection: keep-alive
Location: http://html.md5.cn/img.md5.cn/www/

html.md5.cn這個功能變數名稱並非公佈的功能變數名稱,返回給用戶端是會自然產生錯誤的
Nginx可以很好的處理這個問題:

server {
  server_name img.md5.cn;
  location / {
    rewrite ^(.*) /$http_host$1 break;
    proxy_set_header Host html.md5.cn;
    proxy_pass http://cache-89;
    proxy_redirect   http://html.md5.cn/img.md5.cn/    /;
  }
}

 

加一行proxy_redirect後,正常了:

[root@aslibra ~]# curl -I http://img.md5.cn/www
HTTP/1.1 301 Moved Permanently
Server: nginx/0.7.59
Date: Tue, 21 Jul 2009 15:23:49 GMT
Content-Type: text/html
Location: http://img.md5.cn/www/
Connection: keep-alive
Content-Length: 185
Expires: Tue, 21 Jul 2009 16:23:49 GMT
Cache-Control: max-age=3600

就這麼樣就ok啦~
不過貌似不支援變數出現在位址裡,這個就鬱悶了,必須指定相應功能變數名稱。
對於多個功能變數名稱匹配的server,redirect設置不能寫作'/'了,否則會用第一個功能變數名稱作為redirect功能變數名稱
可以寫幾個匹配規則:

proxy_redirect   http://html.md5.cn/img.md5.cn/    http://img.md5.cn/;
proxy_redirect   http://html.md5.cn/css.md5.cn/    http://css.md5.cn/;

原文出處:http://www.md5.cn/redirect.php?tid=164&goto=lastpost

By tony

自由軟體愛好者~喜歡不斷的思考各種問題,有新的事物都會想去學習嘗試 做實驗並熱衷研究 沒有所謂頂天的技術 只有謙虛及不斷的學習 精進專業,本站主要以分享系統及網路相關知識、資源而建立。 Github http://stnet253.github.io

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料