简体   繁体   中英

Change NGINX root location depending on server_name

I'm trying to specify root location depending on server_name using it's variable. I have configuration like this one below:

server {
    listen       80;
    server_name  ~^(host1|host2)\.example\.com$;

    access_log  /var/log/nginx/hosts_access.log main;
    error_log   /var/log/nginx/hosts_error.log;

    if ($server_name = host1.example.com) { 
        set $root_path /var/www/host1; 
    }

    if ($server_name = host2.example.com) { 
        set $root_path /var/www/host2; 
    }

    root $root_path;

    location = /robots.txt { return 200 "User-agent: *\nDisallow: /\n"; }

    location / {
        index  index.html;
        try_files $uri $uri/ /index.html =404;
    }

    location ~* \.(jpe?g|png|gif|ico)$ {
        expires 1h;
        access_log off;
    }

    location ~ /\.(ht|svn|git) {
        deny all;
    }
}

Actually I realize that this configuration can be not properly set, but nginx didn't find any errors with nginx -t command. iIs it possible to make config this way? Should I use $http_host/$host instead $server_name as a variable?

You can change the root by using a variable from the regex.

server {
    listen 80;
    server_name     ~^(?<subdomain>.+)\.example\.com$;

    root /var/www/$subdomain;
    ...
}

If you name your variable in the regex you can use it throughout the server block. This makes it much easier then if statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM