2010-05-07 118 views
6

另一個nginx的重寫規則問題:nginx的子域重寫

我怎樣才能做到從http://www.*.domain.comhttp://*.domain.com重寫?從服務器故障

+0

類似的問題:http://stackoverflow.com/questions/2498712/nginx-subdomain-rewrite – 2010-05-13 07:32:18

回答

7
if ($host ~* www\.(.*)) { 
    set $host_without_www $1; 
    rewrite ^(.*)$ http://$host_without_www$1 permanent; # $1 contains '/foo', not 'www.mydomain.com/foo' 
} 

答: https://serverfault.com/questions/139579/nginx-subdomain-rewrite

+5

不推薦使用這種方法現在。參見[關於常見陷阱的這一部分](http://wiki.nginx.org/Pitfalls#Using_If)。 – 2013-01-12 21:30:59

+0

推薦的方法是什麼? – Tony 2013-01-15 14:00:57

2
server { 
    listen 80; 
    listen 443; 
    server_name ~^www\.(\w+)\.domain\.com$; 
    location/{ 
    rewrite^$scheme://$1.domain.com$request_uri? permanent; 
    } 
} 
+0

請注意,這會產生一個雙查詢字符串,對'/?foo = bar'的請求將重定向到'/?foo = bar?foo = bar'。使用'$ uri'似乎按預期工作,但可能有更好的選擇。 – sapht 2012-08-11 18:37:32

+1

添加? $ request_uri之後將避免重複查詢字符串問題。 – tarkeshwar 2012-09-01 20:00:32

+0

server_name後面缺少分號 – alvin 2013-05-23 01:03:18