Hack multiple conditions in Nginx configuration

We @ Gogobot use Nginx for basically every user facing
web service. Whether it’s our main web-app or a microservice.

Even for Docker, we use nginx and not the default Docker proxy that you get
with -p 80:80.

I had a request to add support for trailing slash redirects for all URLs. so
/paris/ will redirect to /paris. and of course /paris/?x=x will also
redirect correctly with all of the parameters.

If you know nginx configuration you know this is a bit tricky, but you can get
around it using an equally tricky hack.

Let’s dive in

What I want is to redirect trailing slashes only for GET and also have
different redirects when there’s a query string and when there isn’t.

Here’s the code:

location ~ ^\/(?!blog)(.*)\/$ {
  set $_url_status "";

  if ($request_method = GET ) {
    set $_url_status "${_url_status}get";

  if ($query_string) {
    set $_url_status "${_url_status}_with_query_string";

  if ( $_url_status = "get" ) {
    return 302 $scheme://stg.gogobot.com/$1;

  if ( $_url_status = "get_with_query_string" ) {
    return 302 $scheme://stg.gogobot.com/$1?$query_string;

As you can see here, I am basically building a condition in multiple phases and
then asking whether it’s get OR get_with_query_string and redirecting

Happy Hacking.