3

Is it possible to change the fallback error_page based on the response of the upstream proxy?

upstream serverA {
  server servera.com;
}

upstream serverB {
  server serverb.com;
}

location / {
  proxy_set_header X-Real-IP       $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
  proxy_set_header Host            $host;
  proxy_pass http://serverA;
  proxy_intercept_errors on;

  # if serverA returns 'hard' 404
  # IE returns X-HARD-404=true header
    return 404;
  # else I would like to fallback to server-b
    error_page 403 404 500 502 504 = @serverB;
}

The reason I would like to do this is to an issue with our setup. Usually we send a request to server-a and if that returns a 404, we ask server-b to return the page. In this case, we do not want server-b to return its page, and we want to explicitly return a 404 without trying server-b.

Nathan Lee
  • 131
  • 1
  • 1
  • 5

2 Answers2

4

You could also serve the error page direct from nginx.

If serverA gives a 404, send 404.html from /your/nginx/html/directory/ without involving serverB

server {
    listen 80;

    location / {
        proxy_pass http://serverA/;
        proxy_intercept_errors on;
        proxy_redirect off;
        error_page 404 /404.html;
    }

    location /404.html {
      root /your/nginx/html/directory/;
    }
}
John Auld
  • 594
  • 2
  • 6
0

You could try this:

location / {
    ...
    error_page 404 = @check_header;
    error_page 403 500 502 504 = @serverB;
}

location @check_header {
    if ($upstream_http_x_hard_404) {
        return 404;
    }
    return 403;
    error_page 403 = @serverB;
}
Alexey Ten
  • 8,435
  • 1
  • 34
  • 36