replacing 500 error in nginx auth_request

One of the great things about nginx is the auth_request module. It allows you to make a call to another URL to authenticate or authorize a user. For my current work that is perfect since virtuall everything follows a RESTful model.

Unfortunately, there is one problem. If the auth_request fails, the server responds with an HTTP status of 500. That normally is a bad thing since it indicates a much more severe problem than a failed authentication or authorization.

The logs indicate that

auth request unexpected status: 400 while sending to client

and then proceeds to return a 500 to the client.

Nginx offers some ways to trap certain proxy errors for fastcgi_intercept_errors and uwsgi_intercept_errors as described in this post. The suggested proxy_intercept_errors off;, doesn’t seem to do the trick either.

I managed to come up with a way that returns a 401 by using the following in the location block that performs the auth_request:

auth_request /auth;
error_page 500 =401 /error/401;

This captures the 500 returned and changes it to a 401. Then I added another location block for 401:

location /error/401 {
   return 401;

Now I get a 401 instead of the 500.

Much better.

On a side note it seems that someone else is also thinking about this.