Nginx 遵循重定向和反向代理最后位置

bed*_*dre 5 redirect reverse-proxy nginx

我正在尝试反向代理一个内部有 N 重定向 301 的 URL。
\n我想跟踪所有页面,然后反向代理最后一个页面(fourth-url.php)。

\n\n

Nginx 有双重功能吗?

\n\n

这是场景

\n\n

第一个网址:

\n\n

http://first-domain.com/first-url.php

\n\n

重定向至

\n\n

http://first-domain.com/second-url.php

\n\n

重定向至

\n\n

http://first-domain.com/third-url.php

\n\n

重定向至(最后一个)

\n\n

http://first-domain.com/fourth-url.php

\n\n

这是我到目前为止所做的文件配置:

\n\n
server {\n\n  set $base_url \'http://first-domain.com\';\n  set $page \'first-url.php\'\n\n  location /myserver {\n     resolver 8.8.8.8;\n     proxy_set_header X-Real-IP  $remote_addr;\n     proxy_set_header X-Forwarded-For $remote_addr;\n     proxy_set_header Host $host;\n     proxy_pass $base_url/$page;\n     proxy_intercept_errors on;\n     error_page 301 302 307 = @handle_redirect;\n  }\n\n  location @handle_redirect {\n     resolver 8.8.8.8;\n     set $saved_redirect_location $upstream_http_location;\n     proxy_set_header X-Real-IP  $remote_addr;\n     proxy_set_header X-Forwarded-For $remote_addr;\n     proxy_set_header Host $host;\n     proxy_pass $base_url/$saved_redirect_location;\n     proxy_intercept_errors on;\n     error_page 301 302 307 = @handle_redirect;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这应该作为递归函数工作,但也许我缺少 if 语句或最后一部分。

\n\n

实际上它的工作原理是这样的:

\n\n

http://first-domain.com/first-url.php [确定]
\n http://first-domain.com/second-url.php [确定]

\n\n

然后 nginx 停止一切并返回:

\n\n
HTTP request sent, awaiting response... 302 Moved Temporarily\nLocation: unspecified\nERROR: Redirection (302) without location.\n
Run Code Online (Sandbox Code Playgroud)\n\n

旁注:first-url.php、second-url.php 等 \xe2\x80\xa6 仅包含一行简单的代码来进行重定向:

\n\n
header("Location: second-url.php");\n
Run Code Online (Sandbox Code Playgroud)\n\n

任何提示/想法表示赞赏。

\n

小智 1

解决方案:添加 recursive_error_pages 指令。

server {
...
proxy_intercept_errors on;
recursive_error_pages on;
error_page 301 302 303 307 308 = @handle_redirect;
...
}
Run Code Online (Sandbox Code Playgroud)

另外,根据nginx recursion limit,你不必担心循环重定向问题,因为 nginx 将递归限制设置为 10。