Tag Archives: conditional

To ensure the best possible quality of service we want to make sure that we catch our uWSGI application failures on the nginx side and react accordingly. Our goal is to never serve a HTTP 500 error to visitors. I’ll show you how you can adapt nginx error handling behavior based on the URI called by the visitor.

nginx + uWSGI base configuration (nginx.conf)

Suppose we have the following configuration to handle our uWSGI apps. We have set our gateway timeouts to 10 seconds to make sure no request will take more than that time to be answered, no matter what our application do.

The uwsgi_intercept_errors directive tells nginx to handle errors from uWSGI. Then we just have to use the usual nginx error handling using the error_page directive which in our case calls for /px.gif, returning our 1×1 GIF pixel using the empty_gif nginx module.

Upon HTTP 500/504 error, the @uwsgi_errors location is called by nginx internals. Let’s detail its processing :

rewrite_log on : turn the rewriting logging on for debugging / monitoring reasons

$arg_redir ~* (.+) : $arg_PARAMETER is a neat way to get the value of the given GET parameter (redir in our case). The condition here means that if the parameter is present, we’ll use it and enter the condition.

rewrite ^ $redir? redirect : we call the rewrite module using the redirect method to send a HTTP 302 to the client with the value of the previously defined $redir variable which contains the URI of the redir parameter. The important part here is the question mark after the $redir variable which makes sure that the original URI parameters are stripped from the redirection URI.

rewrite ^ /px.gif? redirect : if no redir parameter was received, we redirect to the the px.gif as usual. The question mark has the same meaning as above.

That’s it, we managed to handle our uWSGI errors based on certain conditions. Of course we could go further and use more named locations for different types of HTTP errors and use more nginx variables and conditions but that’s up to you now !