I would like to set the variable $sub conditionally dependent on $request_uri and $host.

map $request_uri $sub {
    default       front;
    ~^/api/.*     api;
    ~^/rest/.*    rest;

map $host $sub {

    #default    $sub; # Tried, no success

    ping.*     ping;
    admin.*    admin;

server {
    listen 80;
    server_name _;

    root /usr/share/nginx/html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_param HTTP_X_SUB $sub;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;

    location / {
        try_files $uri $uri/ /index.php;;

I thought nginx will not overwrite $sub in map $host $sub if the hostname is not in the list, but unfortunatly it just blanks out $sub.

So basically it should be like if $host is "ping" or "admin" set $sub accordingly. If hostname did not match, check for $request_uri.

Any idea how to archive that statement?

EDIT: Extended the config.

  • You seem to be checking two different contexts. You probably need two different variables. What do you actually intend to do with this variable? – Michael Hampton Jun 12 at 18:41
  • The second map needs a new variable name, which is then used in the add_header statement. Otherwise, using a map variable as the default of another map works perfectly well. – Richard Smith Jun 12 at 20:02
  • @RichardSmith As you can see, I tried using $sub as default of the second map. No success. It' just empty then. $sub defines the internal working dir and it can not be devided into two variables. – Aley Jun 13 at 9:36
  • The problem is that you have used the same variable for both maps. Use a different name and it will work. – Richard Smith Jun 13 at 10:04
  • @RichardSmith I want to avoid ifs in nginx. I thought nginx can take another variable as default, which is not the case obviously. – Aley Jun 13 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.