Nginx – Change error_page based on proxy_pass response

http-headersnginx

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.

Best Answer

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