'Nginx follow redirect and reverse proxy last location

I'm trying to reverse proxy an URL that have a N redirect 301 inside.
I want to follow all the pages and then reverse proxy the last page (fourth-url.php).

Is something douable with Nginx?

This is the scenario

FIRST URL:

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

REDIRECT TO

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

REDIRECT TO

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

REDIRECT TO (last one)

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

This is the file configuration that I've made until now:

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;
  }
}

This should work as recursive function, but maybe I am missing an if statement or the last part.

Actually it works like this:

http://first-domain.com/first-url.php [OK]
http://first-domain.com/second-url.php [OK]

then nginx stop everything and return:

HTTP request sent, awaiting response... 302 Moved Temporarily
Location: unspecified
ERROR: Redirection (302) without location.

Side note: first-url.php, second-url.php, etc … contain just a simple line of code to make the redirect:

header("Location: second-url.php");

Any hints/ideas appreciated.



Solution 1:[1]

Solution: Add recursive_error_pages directive.

server {
...
proxy_intercept_errors on;
recursive_error_pages on;
error_page 301 302 303 307 308 = @handle_redirect;
...
}

Additionally, according to nginx recursion limited, you do not have to worry about circular redirection problem since nginx set the recursion limitation to 10.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yiwei Mao