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

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

这是我目前想到的办法,部分可行。我不明白如何检查主机后是否没有路径/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?; }
}

相关内容