如何遵循Nginx中的HTTPredirect?

我有一个基于nginx的HTTP代理,我想处理其中的所有HTTPredirect,以便客户端只获取redirect链中的最后一个响应。

基本代码如下所示:

location /proxy { rewrite ^/proxy/([^/]+) $1 break; proxy_pass http://$uri/; } 

我试图遵循1级redirect是这样的:

 error_page 301 302 307 =200 @redir; 

…有这个命名的位置:

 location @redir { proxy_pass $proxy_location; } 

只有没有$ proxy_locationvariables,我没有find一个方法来创build它。 它应该包含从上游收到的Location:头的值。

有什么想法吗?

我相信你想variables$ upstream_http_location 。

以$ proxy *开始的variables控制从nginx到上游的variables。 $ upstream *系列variables包含有关nginx自身收到的响应的信息。 您可以使用$ upstream_http_headername从上游服务器获取任何任意HTTP头。

请注意,在从上游服务器收到响应之前,这些$上游variables不能是任何内容,因此它们的使用有一些限制。

以下是对我有用的完整示例:

 server { ... location / { proxy_pass http://backend; # You may need to uncomment the following line if your redirects are relative, eg /foo/bar #proxy_redirect / /; proxy_intercept_errors on; error_page 301 302 307 = @handle_redirect; } location @handle_redirect { set $saved_redirect_location '$upstream_http_location'; proxy_pass $saved_redirect_location; } }