【问题标题】:nginx rewrite all subdomains to wwwnginx将所有子域重写为www
【发布时间】:2013-01-13 07:04:23
【问题描述】:

我正在尝试找到正确的正则表达式来将所有子域重写为 www。

例如 w7w.domain.com 到 www.domain.com

或 alskdaslkdja.domain.com 到 www.domain.com

我尝试了很多东西, 我最后一次尝试是:

if ($host ~* (?!www\.)(.*))
{
  set $host_without_www www.$1;
  rewrite ^(.*)$ http://$host_without_www$1 permanent; 
}

但这也没有用。

我需要抓住这些,不能只是对 www.domain.com 进行通配符重写 因为我有几个域在这个实例上提供服务。

有什么想法吗?

【问题讨论】:

    标签: regex nginx rewrite


    【解决方案1】:
    server {
        listen          xx.xx.xx.xx:80;
        server_name     www.example.com;
        # ....
    }
    server {
        listen          xx.xx.xx.xx:80;
        server_name     example.com *.example.com;
        rewrite         ^ http://www.example.com$request_uri? permanent;
    }
    

    【讨论】:

    • 谢谢,但就像我说的那样,我不能这样做,因为我有很多域是通过这个服务提供的,我无法为所有这些域创建一个服务器条目。
    【解决方案2】:
    server {
      # Prefix server wildcards are checked before regexes, so this
      # will catch anything starting with www.
      server_name www.*;
    }
    
    server {
      # This should redirect anything that didn't match the first
      # server to domain.tld
    
      # I think this regex will capture the domain.tld
      server_name ~(?<domain>[^.]+\.[^.]+)$
    
      rewrite ^ http://www.$domain$request_uri? permanent;
    }
    

    【讨论】:

    • 啊这也行不通,因为我还有其他子域在盒子上运行。 (mail.example.com 等),这会打破我的想法。
    • Regex 服务器名称最后评估。如果您有服务器 { server_name mail.example.com; } 甚至 server { server_name mail.*; } 那么它会在正则表达式 server_name 之前匹配。
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    相关资源
    最近更新 更多