2012-01-25 54 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