掌握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。

示例

设后端服务器为http://example.shizhanxia.com,Nginx代理监听http://shizhanxia.com,后端返回内部重定向URL,需调整为外部可访问地址。

示例1:使用default

server {
    listen 80;
    server_name shizhanxia.com;
    location / {
        proxy_pass http://example.shizhanxia.com;
        proxy_redirect default;
    }
}

当客户端访问http://shizhanxia.com时,Nginx会将请求代理至http://example.shizhanxia.com。经与后端交互,若后端返回重定向,比如重定向到http://example.shizhanxia.com/some/path,由于配置了proxy_redirect default,Nginx会将此重定向地址调整为http://shizhanxia.com/some/path再返回给客户端。

示例2:自定义替换

server {
    listen 80;
    server_name shizhanxia.com;
    location / {
        proxy_pass http://example.shizhanxia.com;
        proxy_redirect http://example.shizhanxia.com/ http://shizhanxia.com/;
    }
}

如此配置后,若后端服务器返回以http://example.shizhanxia.com/开头的重定向URL,Nginx会依规则替换。如重定向URL为http://example.shizhanxia.com/login,经Nginx处理会变为http://shizhanxia.com/login,再返回给客户端,助其精准访问目标地址。

示例3:禁用proxy_redirect

server {
    listen 80;
    server_name shizhanxia.com;
    location / {
        proxy_pass http://example.shizhanxia.com;
        proxy_redirect off;
    }
}

此配置下,后端重定向URL不被修改,直接返回客户端。

原创文章,作者:运维侠,如若转载,请注明出处:https://www.yunweixia.com/knowledgebase/mastering-three-configuration-methods-for-proxy_redirect-in-nginx.html

(0)
运维侠的头像运维侠共建用户
上一篇 2025年9月20日 21:51
下一篇 2025年7月23日 18:11

相关推荐

发表回复

登录后才能评论