Nginx下proxy_redirect的三种配置方式
- 开源代码
- 2025-09-01 06:33:02

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 ,Nginx代理监听http://shizhanxia ,后端返回内部重定向URL,需调整为外部可访问地址。</p><h3>示例1:使用default</h3><pre>server {listen 80;server_name shizhanxia ;location / {proxy_pass http://example.shizhanxia ;proxy_redirect default;}}</pre><p>当客户端访问http://shizhanxia 时,Nginx会将请求代理至http://example.shizhanxia 。经与后端交互,若后端返回重定向,比如重定向到http://example.shizhanxia /some/path,由于配置了proxy_redirect default,Nginx会将此重定向地址调整为http://shizhanxia /some/path再返回给客户端。</p><h3>示例2:自定义替换</h3><pre>server {listen 80;server_name shizhanxia ;location / {proxy_pass http://example.shizhanxia ;proxy_redirect http://example.shizhanxia / http://shizhanxia /;}}</pre><p>如此配置后,若后端服务器返回以http://example.shizhanxia /开头的重定向URL,Nginx会依规则替换。如重定向URL为http://example.shizhanxia /login,经Nginx处理会变为http://shizhanxia /login,再返回给客户端,助其精准访问目标地址。</p><h3>示例3:禁用proxy_redirect</h3><pre>server {listen 80;server_name shizhanxia ;location / {proxy_pass http://example.shizhanxia ;proxy_redirect off;}}</pre><p>此配置下,后端重定向URL不被修改,直接返回客户端。</p>Nginx下proxy_redirect的三种配置方式由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Nginx下proxy_redirect的三种配置方式”