server { server_name domain.com www.domain.com *.domain.com ; set $subdomain ''; if ($host ~* (\b(?!www\b).+)\.domain.com) { set $subdomain -$1; } root /home/user/www$subdomain/; }