title: <Nginx> How to setup Multi dynamic virtual hosts + www + subdomain
body: <p>There are some questions about nginx virtual hosts and subdomain configuration,
  but it can't achieve.</p>
  
  <p>I hava 3 domain and an IP address(Multi-Site) </p>
  
  <pre><code>www.a1.com
  www.a2.com
  www.a3.com
  </code></pre>
  
  <p>I want to use a easy nginx configuration to set up it, and when I enter</p>
  
  <p><strong>URL Rewrites</strong></p>
  
  <pre><code>a1.com      =&gt; force redirect non-www to WWW url www.a1.com
  
  www.a1.com      =&gt; pass to /usr/share/nginx/html/a1.com/
  www.blog.a1.com =&gt; pass to /usr/share/nginx/html/a1.com/blog/
  *www.photo*.a1.com=&gt; pass to /usr/share/nginx/html/a1.com/*photo*/
  ...and so on
  
  a2.com      =&gt; force redirect non-www to WWW url www.a2.com
  
  www.a2.com      =&gt; pass to /usr/share/nginx/html/a2.com/
  www.blog.a2.com =&gt; pass to /usr/share/nginx/html/a2.com/blog/
  www.photo.a2.com=&gt; pass to /usr/share/nginx/html/a2.com/photo/
  www.user.a2.com=&gt; pass to /usr/share/nginx/html/a2.com/user/
  ...and so on
  </code></pre>
  
  <p>a1, a2 and a3.com are using the same configuration.</p>
  
  <p>This is my first code, how can i fix it?</p>
  
  <blockquote>
    <p><strong>pseudo code</strong></p>
  </blockquote>
  
  <pre><code>if subdomain lacks 'www' then pass to $scheme://www.$host$request_uri;
  if subdmain &lt;&gt;'' then pass to /usr/share/nginx/html/$host/&lt;#subdmain#&gt;/$request_uri;
  </code></pre>
  
  <blockquote>
    <p><strong>/etc/nginx/conf.d/default.conf</strong></p>
  </blockquote>
  
  <pre><code>server {
      # Redirect non-www to WWW
      server_name "~^(?!www\.).*" ;
      return 301 $scheme://www.$host$request_uri;
  }
  
  server {
  
      listen 80 default;
  
      #automatic judging hostname
      server_name  ~^(www\.)?(?&lt;domain&gt;.+)$;
  
      location / {
  
          #automatic change folder
          root    /usr/share/nginx/html/$domain/;
  
          index index.html index.php;
          #try_files $uri $uri/ /index.php?$query_string;
      }
  
      # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  
      location ~ \.php$ {
          fastcgi_pass   127.0.0.1:9000;
          fastcgi_index  index.php;
  
          # judging subdomain which have "www"
          if ($subdomain = 'www') {
              fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$domain$fastcgi_script_name;
          }
          # judging subdomain like "blog" and trans to blog folder
          else {
              fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$domain/$subdomain/$fastcgi_script_name;
          }
          include    fastcgi_params;
      }
  }
  </code></pre>