Nginx中的proxy_redirect指令,用于修改代理服務器接收到的后端服務器響應中的重定向URL。在代理環境中,若后端返回的重定向URL不符合客戶端需求,就用它調整。
語法
proxy_redirect default;
proxy_redirect redirect replacement;
proxy_redirect off;
default:Nginx按proxy_pass設置自動調整重定向 URL。 redirect replacement:redirect是原始重定向URL模式,replacement是替換后的URL。 off:禁用此功能,不修改重定向URL。
示例 | |
<p>設后端服務器為http://example.shizhanxia.com,Nginx代理監聽http://shizhanxia.com,后端返回內部重定向URL,需調整為外部可訪問地址。</p> | |
<h3>示例1:使用default</h3> | |
<pre>server { | |
listen 80; | |
server_name shizhanxia.com; | |
location / { | |
proxy_pass http://example.shizhanxia.com; | |
proxy_redirect default; | |
} | |
} | |
</pre> | |
<p>當客戶端訪問http://shizhanxia.com時,Nginx會將請求代理至http://example.shizhanxia.com。經與后端交互,若后端返回重定向,比如重定向到http://example.shizhanxia.com/some/path,由于配置了proxy_redirect default,Nginx會將此重定向地址調整為http://shizhanxia.com/some/path再返回給客戶端。</p> | |
<h3>示例2:自定義替換</h3> | |
<pre>server { | |
listen 80; | |
server_name shizhanxia.com; | |
location / { | |
proxy_pass http://example.shizhanxia.com; | |
proxy_redirect http://example.shizhanxia.com/ http://shizhanxia.com/; | |
} | |
} | |
</pre> | |
<p>如此配置后,若后端服務器返回以http://example.shizhanxia.com/開頭的重定向URL,Nginx會依規則替換。如重定向URL為http://example.shizhanxia.com/login,經Nginx處理會變為http://shizhanxia.com/login,再返回給客戶端,助其精準訪問目標地址。</p> | |
<h3>示例3:禁用proxy_redirect</h3> | |
<pre>server { | |
listen 80; | |
server_name shizhanxia.com; | |
location / { | |
proxy_pass http://example.shizhanxia.com; | |
proxy_redirect off; | |
} | |
} | |
</pre> | |
<p>此配置下,后端重定向URL不被修改,直接返回客戶端。</p> |