sunshine
sunshine

Reputation: 1963

nginx: empty subdomain can not work

I read this article http://bneijt.nl/blog/post/name-based-virtual-hosting-with-nginx/
and excerpts is as follow:

server {
    server_name ~^((?<subdomain>.*)\.)?(?<domain>[^.]+)\.(?<tld>[^.]+)$;
    if ($subdomain = "") {
        set $subdomain "_";
    }
    location / {
        index index.html;
        root /srv/http/vhost/${domain}.${tld}/${subdomain};
    }
}

I imitate it and write my configuration like this:

server {
    server_name  ~^((?<subdomain>.*)\.)aa\.com$;
    if ($subdomain = "") {
        set $subdomain "www";
    }

    location / {
        root   /var/www/${subdomain}.aa.com/public;
        index  index.html index.htm;
    }
}

Every subdomain corresponds to it's folder,like this:

domain name    folder
111.aa.com     /var/www/111.aa.com
222.aa.com     /var/www/222.aa.com

Question:
If input www.aa.com,it works,but input aa.com,it cann't work,domain name resolution is ok,what's the problem?

Upvotes: 2

Views: 383

Answers (1)

num8er
num8er

Reputation: 19372

Try this:

server {
    server_name  ~^((?<subdomain>.*)\.)aa\.com$ aa.com;

      if ($host ~ aa.com) {
          set $subdomain "www";
      }

    location / {
        root   /var/www/${subdomain}.aa.com/public;
        index  index.html index.htm;
    }
}

but I prefer this:

# redirect user to www.aa.com if user went to aa.com
server {
    server_name aa.com;
    return 301 $scheme://www.aa.com$request_uri;
}

# handle subdomain part
server {
    server_name  ~^((?<subdomain>.*)\.)aa\.com$;

    location / {
        root   /var/www/${subdomain}.aa.com/public;
        index  index.html index.htm;
    }
}

Upvotes: 1

Related Questions