Nginx下proxy_redirect的三种配置方式
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> |