nginx:空子域无法正常工作

时间:2016-04-12 14:38:47

标签: nginx

我读过这篇文章http://bneijt.nl/blog/post/name-based-virtual-hosting-with-nginx/
摘录如下:

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

我模仿它并写下我的配置:

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

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

每个子域都对应于它的文件夹,如下所示:

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

问题:
如果输入www.aa.com,它可以正常工作,但输入aa.com,它无法正常工作,域名解析就可以了,问题是什么?

1 个答案:

答案 0 :(得分:1)

试试这个:

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;
    }
}

但我更喜欢这个:

# 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;
    }
}