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

use*_*836 5 rewrite nginx

我是 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
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我想出的,它部分有效。我不明白的是如何检查主机后面是否没有路径/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;
}
Run Code Online (Sandbox Code Playgroud)

kol*_*ack 13

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

# 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?; }
}
Run Code Online (Sandbox Code Playgroud)