Handling errors in nginx in a reverse proxy configuration

I'm using nginx as a reverse-proxy over my existing web server. I only want to manage a single set of custom error pages, and ideally within nginx as this is the level closest to the client.

Now I'm fine with using the error_pages and proxy_intercept_errors settings. However:

  1. In the case of 400 (Bad Request) errors I need the underlying web server to be able to through some JSON body content, detailing why the request was bad. And so I need a way of disabling proxy_intercept_errors for 400 status codes only.

  2. I never want to show the default nginx error pages, for any status code. Now from what I can see, in order to achieve this I would need to explicitally list out every possible status code imaginable, and have an error page for it? Rather than just wildcarding all errors above 500 for example.

My questions are - Are the above 2 issues resolvable within nginx itself? If not, is there an obvious solution to the issues above?


Solution 1:

I hadn't read the documentation correctly. In-fact the bypassing of the rules by a 400 error is a simple as not having an error page directive.

This is from the proxy_intercept_errors documentation entry:

If you set this to on then nginx will intercept status codes that are explicitly handled by an error_page directive. Responses with status codes that do not match an error_page directive will be sent as-is from the proxied server. (emphasis my own)

Solution 2:

Try the following. Include this map in your http context.

map $sent_http_status_code $400 {
  default 0;
  ~400    1;
}

Include the following in your server context (of the proxy of course).

if ($400) {
  proxy_pass (socket|address:port);
}

Regarding your second question. You can specify a single file for more errors like the following:

error_page 500 501 502 503 504 505 /500.html

Wikipedia has all valid HTTP status codes listed with a short explanation: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes