2012-01-25 69 views
1

我试图找到正确的正则表达式来将所有子域重写为www。nginx将所有子域重写为www

因此,例如w7w.domain.com到www.domain.com

或alskdaslkdja.domain.com到www.domain.com

我已经尝试了很多东西,我 最后一次尝试是:

if ($host ~* (?!www\.)(.*)) 
{ 
    set $host_without_www www.$1; 
    rewrite ^(.*)$ http://$host_without_www$1 permanent; 
} 

但这也没有工作。

我需要抓住这些,不能只是做一个wildcart重写到www.domain.com ,因为我有几个域正在这个实例服务。

有什么想法?

回答

1
server { 
    listen   xx.xx.xx.xx:80; 
    server_name  www.example.com; 
    # .... 
} 
server { 
    listen   xx.xx.xx.xx:80; 
    server_name  example.com *.example.com; 
    rewrite  ^http://www.example.com$request_uri? permanent; 
} 
+0

感谢,但就像我说的,我不能做这种方式,因为我有一个正在从这种服务的诸多领域,我没有能力创造为所有这些服务器条目。 –

0
server { 
    # Prefix server wildcards are checked before regexes, so this 
    # will catch anything starting with www. 
    server_name www.*; 
} 

server { 
    # This should redirect anything that didn't match the first 
    # server to domain.tld 

    # I think this regex will capture the domain.tld 
    server_name ~(?<domain>[^.]+\.[^.]+)$ 

    rewrite^http://www.$domain$request_uri? permanent; 
} 
+0

啊这也行不通,因为我还有其他的子域也在运行。 (mail.example.com等),这将打破我的想法。 –

+0

最后评估正则表达式服务器名称。如果你有一台服务器{server_name mail.example.com; }甚至服务器{server_name mail。*; }然后它会匹配正则表达式server_name。 – kolbyjack