Redirect 是否可能拦截后端301/302重定向(代理传递)并重写到另一个位置块?

Redirect 是否可能拦截后端301/302重定向(代理传递)并重写到另一个位置块?,redirect,nginx,http-status-code-301,reverse-proxy,http-status-code-302,Redirect,Nginx,Http Status Code 301,Reverse Proxy,Http Status Code 302,我们的nginx前端后面有几个后端 是否可以拦截这些后端发送的301/302重定向,并让nginx处理它们 我们独自思考着一些事情,比如: error_page 302 = @target; 但我怀疑301/302重定向是否可以像404等一样处理。。。我的意思是,错误页面可能不适用于200等错误代码 因此,总结一下: 我们的后端偶尔会发送回301/302。我们想让nginx截取这些,并将它们重写到另一个位置块,在那里我们可以用它们做任何其他事情 可能吗 谢谢 您可以使用proxy\u redi

我们的nginx前端后面有几个后端

是否可以拦截这些后端发送的301/302重定向,并让nginx处理它们

我们独自思考着一些事情,比如:

error_page 302 = @target;
但我怀疑301/302重定向是否可以像404等一样处理。。。我的意思是,错误页面可能不适用于200等错误代码

因此,总结一下:

我们的后端偶尔会发送回301/302。我们想让nginx截取这些,并将它们重写到另一个位置块,在那里我们可以用它们做任何其他事情

可能吗


谢谢

您可以使用
proxy\u redirect
指令:

Nginx仍将301/302返回给客户端,但
代理重定向
将修改
位置
头,客户端应向
位置
头中给出的URL发出新请求

类似这样的内容会使后续请求返回到nginx:

proxy\u重定向http://upstream:port/    http://$http_host/


我成功地解决了一个更一般的情况:重定向位置可以是任何外部URL

server {
    ...

    location / {
        proxy_pass http://backend;
        # You may need to uncomment the following line if your redirects are relative, e.g. /foo/bar
        #proxy_redirect / /;
        proxy_intercept_errors on;
        error_page 301 302 307 = @handle_redirects;
    }

    location @handle_redirects {
        set $saved_redirect_location '$upstream_http_location';
        proxy_pass $saved_redirect_location;
    }
}

ServerFault对该问题的回答中介绍了更接近您描述的替代方法:

如果您需要遵循多个重定向,请按如下方式修改Vlad的解决方案:

1) 加

位置/

2) 加


位置@handle\u重定向
部分。

有关
代理\u重定向
的更多信息,了解相对位置

案例
  • 后端重定向到一个相对位置,该位置缺少
    /api/
    前缀
  • 浏览器跟随重定向,撞上了一堵无法理解的墙
解决方案
在代理重定向中使用
$scheme://
而不是http://使其在https上工作。
recursive_error_pages on;
  proxy_intercept_errors on;
  error_page 301 302 307 = @handle_redirect;
location /api/ {
  proxy_pass http://${API_HOST}:${API_PORT}/;
}
location /api/ {
  proxy_pass http://${API_HOST}:${API_PORT}/;
  proxy_redirect ~^/(.*) http://$http_host/api/$1;
}