![nginx 使用域名主机重定向到特定内部目录的重写规则](https://linux22.com/image/553731/nginx%20%E4%BD%BF%E7%94%A8%E5%9F%9F%E5%90%8D%E4%B8%BB%E6%9C%BA%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%E7%89%B9%E5%AE%9A%E5%86%85%E9%83%A8%E7%9B%AE%E5%BD%95%E7%9A%84%E9%87%8D%E5%86%99%E8%A7%84%E5%88%99.png)
我是 Nginx 重写的新手,正在寻求帮助以获取可行且最小的重写代码。我们想在活动材料上使用类似“somecity.domain.com”的 URL,并将结果转到“www”网站内的特定城市内容。
因此,如果客户输入以下用例:
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
这是我目前想到的办法,部分可行。我不明白如何检查主机后是否没有路径/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;
}
答案1
最好使用三台服务器来实现:
# 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?; }
}