NginX prefered scheme

Here is another usefull use-case for map.

Suppose, we have an unified vhost-setup (SSL/non-SSL) and wish handle some URLs encrypted, some other non-encryted and some we don't care about.

First, let's map $uri to desired scheme:

map $uri $prefered_scheme {
    default         "http";
    ~^/admin        "https";
    ~^/robots\.txt  $scheme;    # whatever
}

Then, we adjust our config as follows:

server {
    listen 80 default;
    listen 443 default ssl;

    # ...

    if ($prefered_scheme != $scheme) {
        return 301 $prefered_scheme://$host$request_uri;
    }

    # ....
}

This way, the admin interface is always handled encrypted, any other content as non-encryted and robots.txt both.

By Dimitri Sokolyuk
Related articles