nginx 拦截后端301/302重定向(proxy_pass)并重写到另一个位置块可能吗?

cetgtptt  于 4个月前  发布在  Nginx
关注(0)|答案(4)|浏览(69)

我们有一对夫妇的后端坐在我们的nginx前端后面。
有没有可能拦截这些后端发送的301 / 302重定向,并让nginx处理它们?
我们在想一些事情

error_page 302 = @target;

字符串
但我怀疑301/302重定向可以处理相同的404等...我的意思是,错误页可能不适用于200等错误代码?
所以总结一下:
我们的后端偶尔会发回301/302。我们希望nginx截获这些,并将它们重写到另一个位置块,在那里我们可以用它们做任何其他事情。
有可能吗?
谢谢你,谢谢

iugsix8n

iugsix8n1#

你可以使用proxy_redirect指令:
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect
Nginx仍然会向客户端返回301/302,但是proxy_redirect会修改Location头,客户端应该向Location头中给出的URL发出新的请求。
类似这样的东西应该会将后续的请求返回到nginx:
proxy_redirect http://upstream:port/ http://$http_host/;

eqoofvh9

eqoofvh92#

我成功地解决了一个更一般的情况,即重定向位置可以是任何外部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回答此问题时介绍:https://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally

qfe3c7zg

qfe3c7zg3#

如果您需要遵循多个重定向,请按如下所示修改Vlad的解决方案:
1.添加

recursive_error_pages on;

字符串
转换为location / .
1.添加

proxy_intercept_errors on;
   error_page 301 302 307 = @handle_redirects;


location @handle_redirects部分。

44u64gxh

44u64gxh4#

关于proxy_redirect的更多信息,用于相对位置

案例

location /api/ {
  proxy_pass http://${API_HOST}:${API_PORT}/;
}

字符串

  • 后端重定向到一个相对位置,这会丢失/api/前缀
  • 浏览器跟随重定向并碰到一堵不理解的墙

溶液

location /api/ {
  proxy_pass http://${API_HOST}:${API_PORT}/;
  proxy_redirect ~^/(.*) http://$http_host/api/$1;
}

相关问题