nginx将所有子域重写为www

时间:2012-01-25 09:13:48

标签: regex nginx rewrite

我正在尝试找到正确的正则表达式,将所有子域重写为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进行野外重写 因为我在这个实例上提供了几个域。

任何想法?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

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;
}