我正在尝试反向代理一个内部有 N 重定向 301 的 URL。
我想跟踪所有页面,然后反向代理最后一页(fourth-url.php)。
Nginx 有双重功能吗?
这是场景
第一个网址:
http://first-domain.com/first-url.php
重定向至
http://first-domain.com/second-url.php
重定向至
http://first-domain.com/third-url.php
重定向到(最后一个)
http://first-domain.com/fourth-url.php
这是我到目前为止所做的文件配置:
server {
set $base_url 'http://first-domain.com';
set $page 'first-url.php'
location /myserver {
resolver 8.8.8.8;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_pass $base_url/$page;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirect;
}
location @handle_redirect {
resolver 8.8.8.8;
set $saved_redirect_location $upstream_http_location;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_pass $base_url/$saved_redirect_location;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirect;
}
}
这应该作为递归函数工作,但也许我错过了 if 语句或最后一部分。
实际上它是这样工作的:
http://first-domain.com/first-url.php [确定]
http://first-domain.com/second-url.php [确定]
然后nginx停止一切并返回:
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: unspecified
ERROR: Redirection (302) without location.
旁注:first-url.php、second-url.php 等……只包含一行简单的代码来进行重定向:
header("Location: second-url.php");
任何提示/想法表示赞赏。
最佳答案
解决方案:添加 recursive_error_pages 指令。
server {
...
proxy_intercept_errors on;
recursive_error_pages on;
error_page 301 302 303 307 308 = @handle_redirect;
...
}
此外,根据 nginx recursion limited ,您不必担心循环重定向问题,因为 nginx 将递归限制设置为 10。
关于redirect - Nginx 跟随重定向和反向代理最后一个位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42021218/