nginx重写规则,使用域名主机redirect到特定的内部目录

我是Nginx重新编写的新手,希望获得工作和最小的重写代码方面的帮助。 我们希望在广告系列材料上使用诸如“somecity.domain.com”之类的url,并将结果转到“www”网站中的城市特定内容。

所以,这里是用例,如果客户input:

www.domain.com (stays) www.domain.com domain.com (goes to) www.domain.com www.domain.com/someuri (stays the same) somecity.domain.com (no uri, goes to) www.domain.com/somecity/prelaunch somecity.domain.com/landing (goes to) www.domain.com/somecity/prelaunch somecity.domain.com/anyotheruri (goes to) www.domain.com/anyotheruri 

这是我到目前为止所做的,部分工作。 我不明白的是如何检查主机后是否没有path/ URI,我猜可能有更好的方法来做到这一点。

 if ($host ~* ^(.*?)\.domain\.com) { set $city $1;} if ($city ~* www) { break; } if ($city !~* www) { rewrite ^/landing http://www.domain.com/$city/prelaunch/$args permanent; rewrite (.*) http://www.domain.com$uri$args permanent; } 

这最好使用三台服务器完成:

 # www.domain.com, actually serves content server { server_name www.domain.com; root /doc/root; # locations, etc } # redirect domain.com -> www.domain.com server { server_name domain.com; rewrite ^ http://www.domain.com$request_uri? permanent; } # handle anything.domain.com that wasn't handled by the above servers server { # ~ means regex server name # 0.8.25+ #server_name ~(?<city>.*)\.domain\.com$; # < 0.8.25 server_name ~(.*)\.domain\.com$; set $city $1; location = / { rewrite ^ http://www.domain.com/$city/prelaunch; } location = /landing { rewrite ^ http://www.domain.com/$city/prelaunch; } # should there be a /$city before $request_uri? location / { rewrite ^ http://www.domain.com$request_uri?; } }