2010-05-07 70 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