NginX maps for fun'n'profit

Suppose you have two or three different backends and wish to avoid a clumpsy solution defining every single location on what goes where. Let's say you have a main page with Django and some blog with WordPress.

Shortly I worked out an interisting solution to achieve it.

For the sake of example, let's assume you have two upstreams: a django backend and a wordpress backend:

upstream django {
    server 127.0.0.1:8000;
}

upstream wordpress {
    server 127.0.0.1:9000;
}

Now, let's define a mapping on $uri to a named location:

map $uri $backend {
    default       @django;
    ~^/blog       @wordpress;
    ~^/wp-admin   @wordpress;
    ~^/wp-content @wordpress;
}

Finaly, in the main session, we simply define a try_files with a mapped value istead of a named location as we would do it otherwise:

server {
    server_name    example.com;
    # more stuff like root etc.

    location / {
        try_files $uri $backend;
    }

    location @django {
        include proxy_params;
        proxy_pass http://django;
    }

    location @wordpress {
        include proxy_params;
        proxy_pass http://wordpress;
    }
}

That's all. The important part is a $backend variable. It decides where the URI is routed to.

By Dimitri Sokolyuk
Related articles