title: how to dynamically root by both domain and subdomain in nginx config
body: <p>I want to host several domain names, each with subdomains dynamically on my nginx server (ubuntu 14.04):</p>
  
  <pre><code>home/serve/
       domain1.com
          www
          subdomain1
          subdomain2
       domain2.com
          www
          subdomain1
          subdomain2
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>server {
      listen 80 default_server;
      listen [::]:80 default_server ipv6only=on;
  
      server_name   ~^(www\.)?(?&lt;domain&gt;.+)$;
  
      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;
      }
  }
  </code></pre>