Nginx auth_request how to return backend status code

authorizationnginx

when the backend proxy used in auth_request returns an error code different from 401 or 403, nginx is returning a 500 error code.

The ngx_http_auth_request_module module (1.5.4+) implements client authorization based on the result of a subrequest. If the subrequest returns a 2xx response code, the access is allowed. If it returns 401 or 403, the access is denied with the corresponding error code. Any other response code returned by the subrequest is considered an error.

Is there a way to make nginx returns the status code from the backend and not 500 ?

Best Answer

I found a working solution. It uses the fact that auth_request will always return a 500 error code in case of a backend error different from 401 or 403 :

error_page 500 @process_backend_error;

location / {
    auth_request /auth
    auth_request_set $backend_status $upstream_status
}

location /auth {
    proxy_pass ...
}

location @process_backend_error {
    # here you have access to $backend_status which contains the returned status code from your autorization backend
}

Beware that the returned status code in $backend_status is a string.