简体   繁体   中英

how to dynamically root by both domain and subdomain in nginx config

I want to host several domain names, each with subdomains dynamically on my nginx server (ubuntu 14.04):

home/serve/
     domain1.com
        www
        subdomain1
        subdomain2
     domain2.com
        www
        subdomain1
        subdomain2

I want both www.domain1.com and domain1.com to root to /home/serve/domain1/www and subdomain1.domain1.com to root to /home/serve/domain1/subdomain1.

I have this working for the domain both with and without www. (see below) but I can't work out how I can extend this to enable the subdomain rooting as well.

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name   ~^(www\.)?(?<domain>.+)$;

    root       /home/serve/$domain/www/;

    location / {
        index index.html index.htm index.php;
    }

    location ~ [^/]\.php(/|$) {
      fastcgi_split_path_info ^(.+?\.php)(/.*)$;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_index index.php;
      include fastcgi_params;
    }
}

You can extend your regular expression to include any subdomain, not just www. Also, it would be a good idea to set up the default folder in case the folder for the requested subdomain does not exist.

Something like this should work fine:

server_name ~^(?<subdomain>\w*?)?\.?(?<domain>\w+\.\w+)$;

if ($subdomain = "") {
    set $subdomain "www";
}

if (!-d "/home/serve/$domain/$subdomain") {
    set $subdomain "www";
}

root "/home/serve/$domain/$subdomain";

Note that even though using the "if" directive is usually inadvisable, in this particular case it is completely safe and acceptable, since these directives are defined in the server context.

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