Nginx – How to return 403 instead 500 response code after auth_request fails

nginx

Is it possible to return a 403 response code after the auth_request nginx module returns with 403, so that a forbidden directive is also shown to the user instead of a 500 internal server error, which is not very informative.

Best Answer

This might help:

If you want to display your own page instead of the default error page provided by DotCloud, you have to use a few tricks.

First, note that this will only work for stacks that embed a Nginx server. For other stacks, DotCloud load balancers will be the only layer between your user and your app, and for now, it can only serve a default error page.

You need to tell Nginx to do all those things:

use a custom static page for 502 and 504 errors; remap the error code to e.g. 500 (else, the DotCloud load balancers will serve the default 502 and 504 pages); intercept the errors sent by the uwsgi/fastcgi (else, our custom static page won’t be used); reduce the default timeout, so your timeout handler will kick in before the platform-wide timeout handler. Assuming your error pages are in /static/502.html and /static/504.html, you can use the following nginx.conf snippets:

PHP:

fastcgi_read_timeout 10;
fastcgi_intercept_errors on;
error_page 502 =500 /static/502.html;
error_page 504 =500 /static/504.html;

Perl/Phython:

uwsgi_read_timeout 10;
uwsgi_intercept_errors on;
error_page 502 =500 /static/502.html;
error_page 504 =500 /static/504.html;

Ruby:

For Ruby applications, since Passenger will use error code 500, no rewriting is needed. The default Nginx configuration already provides a handler for that (errorpage 500 /static/500.html). Also, since Passenger does not expose a configuration variable to change the timeout, you cannot provide a custom 504 page.

Once you enable intercept_errors in Nginx, you can no longer generate your own error pages for e.g. HTTP codes 500, 403, etc. You have to define static pages for those errors in Nginx as well. This limitation will be lifted in a future version of the services.

Source: http://docs.dotcloud.com/guides/5xx/

Otherwise, Check out this page on http://wiki.nginx.org/NginxVariableTutorialCn06 that provides a decent tutorial on it. [Although I recommend translating the page via google chrome...]