NginX Subdomains

nginx

Working on migrating servers and having zero luck setting up my subdomains. The behavior I'm looking for is fairly straightforward:

  • www.domain.com & domain.com –> /var/www/live/
  • *.domain.com –> /var/www/*/ (assuming the sub directory exists, otherwise redirect to main site)

I've tried using $host in a couple of configurations and I've tried using many variations of:

server_name ~^(.*)\.domain\.com$;

root /var/www/$1;

and

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

root /var/www/$subdomain;

This is basic NginX behavior but I'm completely stumped and I've wasted way too many hours trying to hack my way through this. Can anyone shed some light on the solution?

Thanks in advance!

Best Answer

try this:

server {
    listen 80;
    server_name example.com *.example.com;
    root /var/www/example.com/$subdomain;
    set $subdomain "";
    if ($host ~* ^([a-z0-9-\.]+)\.example.com$) {
        set $subdomain $1;
    }
    if ($host ~* ^(www.)?example.com$) {
        set $subdomain "live";
    }

}