nginx conf /w multiple map(s) to same variable

2019-02-27 18:05发布

问题:

we have a multisite set-up and need to map domains and domains/subfolders to a variable. This way the programming knows which version to load.

We have stores that have separate domains and that can be captured by $http_host but also domain.com/-string-locale-here- and are captured by $http_host$uri and a match command

Somehow the below is not working. Can this be because there are two map commands, both mapping towards the same variable $storecode

Or what might be going wrong?

map $http_host $storecode {
 default dom_nl;
 domain.com dom_nl;
 domain.de dom_de;
 store.com str_de;
 }

map $http_host$uri $storecode { 
  ~^store.com/en.* str_en;
  ~^store.com/fr.* str_fr;
}

回答1:

When default is not specified in a map block, the default resulting value will be an empty string. So, in your case, whatever value $storecode is set with in the first map block, it is replaced with an empty string in the second one.

Since map variables are evaluated when they are used, you cannot set $storecode as the default value in the second map block, because that will cause an infinite loop.

So the solution is to introduce a temporary variable in the first map block and then use it as the default value in the second block:

map $host $default_storecode {
    default dom_nl;
    domain.com dom_nl;
    domain.de dom_de;
    store.com str_de;
}

map $host$uri $storecode {
    default $default_storecode;

    ~^store.com/en.* str_en;
    ~^store.com/fr.* str_fr;
}

Alternatively, you can merge these two map blocks into one:

map $host$uri $storecode {
    default           dom_nl;

    ~^domain.com.*    dom_nl;
    ~^domain.de.*     dom_de;

    ~^store.com/en.*  str_en;
    ~^store.com/fr.*  str_fr;
    ~^store.com.*     str_de;
}


标签: nginx