2016-04-12 54 views
2

我讀這篇文章http://bneijt.nl/blog/post/name-based-virtual-hosting-with-nginx/
和摘錄情況如下: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

試試這個:

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