今天在做nginx反向代理apache的時候出了一點點問題,原來后端apache用的端口是8080通過反向代理后,使用wireshark抓包發現location頭域數值為http://192.168.1.154:8080/wuman/ 如果把這個返回給客戶端肯定是不可以的,看起來別扭而且還暴露了apache的具體信息
所以在這里用到了nginx的proxy_redirect指定修改被代理服務器返回的響應頭中的location頭域跟refresh頭域數值
以下是截取nginx的一小段配置文檔
server { listen 80; server_name www.boke.com; location / { proxy_pass http://192.168.1.154:8080; proxy_redirect off; } }
此時我們通過curl查看結果得出
[root@localhost nginx]# curl -I http://www.boke.com/wumanHTTP/1.1 301 Moved PermanentlyServer: nginxDate: Thu, 24 Dec 2015 12:02:00 GMTContent-Type: text/html; charset=iso-8859-1Connection: keep-aliveLocation: http://192.168.1.154:8080/wuman/
這里location為帶有后端服務器實際地址跟端口的響應頭信息這樣在實際線上是不允許的所以這里我們打算通過proxy_redirect將被代理服務器的響應頭中的location字段進行修改后返回給客戶端
server { listen 80; server_name www.boke.com; location / { proxy_pass http://192.168.1.154:8080; proxy_redirect http://192.168.1.154:8080/wuman/ http://www.boke.com/wuman/; }server { listen 80; server_name www.boke.com; location / { proxy_pass http://192.168.1.154:8080; proxy_redirect ~^http://192.168.1.154:8080(.*) http://www.boke.com$1; }
則curl查看返回結果
[root@localhost nginx]# curl -I http://www.boke.com/wumanHTTP/1.1 301 Moved PermanentlyServer: nginxDate: Thu, 24 Dec 2015 12:08:34 GMTContent-Type: text/html; charset=iso-8859-1Connection: keep-aliveLocation: http://www.boke.com/wuman/
此時查看location已經變成了我們想要的結果了。 此時通過replacement 301重定向到了我們新的頁面
出處:
proxy_redirect
語法:proxy_redirect [ default|off|redirect replacement ]
默認值:proxy_redirect default
使用字段:http, server, location
如果需要修改從被代理服務器傳來的應答頭中的"Location"和"Refresh"字段,可以用這個指令設置。
假設被代理服務器返回Location字段為: http://localhost:8000/two/some/uri/
這個指令:
proxy_redirect http://localhost:8000/two/ http://frontend/one/;
將Location字段重寫為http://frontend/one/some/uri/。
在代替的字段中可以不寫服務器名:
proxy_redirect http://localhost:8000/two/ /;
這樣就使用服務器的基本名稱和端口,即使它來自非80端口。
如果使用“default”參數,將根據location和proxy_pass參數的設置來決定。
例如下列兩個配置等效:
location / one / { proxy_pass http: //upstream:port/two/; proxy_redirect default;}location / one / { proxy_pass http: //upstream:port/two/; proxy_redirect http: //upstream:port/two/ /one/;}
在指令中可以使用一些變量:
proxy_redirect http://localhost:8000/ http://$host:$server_port/;
這個指令有時可以重復:
proxy_redirect default;proxy_redirect http://localhost:8000//; proxy_redirect ; /;
參數off將在這個字段中禁止所有的proxy_redirect指令:
proxy_redirect off;proxy_redirect default;proxy_redirect http://localhost:8000/ /; proxy_redirect ; /;
利用這個指令可以為被代理服務器發出的相對重定向增加主機名:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答