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

标签 redirect nginx reverse-proxy

我正在尝试反向代理一个内部有 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/

相关文章:

redirect - 如何将Kotlin stdio重定向到文件?

python如何在重定向后获取最终目的地

redirect - Heroku/GoDaddy : send naked domain to www

node.js - 子目录中带有 NGINX 的多 Node 应用程序

nginx - Nginx 背后的多个 Meteor 站点

linux - curl: (7) 无法连接到端口 80 和 443 - 在一个域上

python - 如何实时将 STDOUT 从导入的模块重定向到 python 中的 Tkinter Text Widget?

Nginx 基于域名的TCP转发

http - Cloudflare 边缘缓存忽略爬虫

linux - haproxy acl中的base/uri/path/etc有什么区别?