NginX:设置多个重定向

时间:2015-01-15 22:57:31

标签: redirect nginx webserver

我试图将一系列域重定向聚合成一个更简单的解决方案。理想情况下,没有they aren't recommended之后的if条件。

由于服务器访问限制,我只能编辑服务器{}块,因此解决方案应考虑此限制。

以下是我目前的一套规则:

server {

  # 301 Redirect domainA.com to www.primaryDomain.com
  if ($host = "domainA.com") {
    rewrite ^ $scheme://www.primaryDomain.com$uri permanent;
  }

  # 301 Redirect www.domainA.com to www.primaryDomain.com
  if ($host = "www.domainA.com") {
    rewrite ^ $scheme://www.primaryDomain.com$uri permanent;
  }

  # 301 Redirect domainB.com to www.primaryDomain.com
  if ($host = "domainB.com") {
    rewrite ^ $scheme://www.primaryDomain.com$uri permanent;
  }

  # 301 Redirect www.domainB.com to www.primaryDomain.com
  if ($host = "www.domainB.com") {
    rewrite ^ $scheme://www.primaryDomain.com$uri permanent;
  }

  # 301 Redirect primaryDomain.com to www.primaryDomain.com
  if ($host = "primaryDomain.com") {
    rewrite ^ $scheme://www.primaryDomain.com$uri permanent;
  }

  # 301 Redirect http to https
  if ($scheme = http) {
    rewrite ^ https://$host$uri;
  }

  ...

}

我还尝试了基于类似question的以下解决方案,但https重定向似乎不起作用:

server {

  listen 80 default_server;
  listen 443 default_server ssl;
  server_name *.domainA.com *.domainB.com *.primaryDomain.com;
  return 301 https://www.primaryDomain.com$request_uri;

}

1 个答案:

答案 0 :(得分:1)

这是我能够提出的最佳解决方案:[1]

server {

  set $redirect false;
  if ($scheme = http) {
    set $redirect true;
  }
  if ($host != "www.primaryDomain.com") {
    set $redirect true;
  }
  if ($redirect = true) {
    return 301 https://www.primaryDomain.com$request_uri;
  }

}

[1]感谢Mike Schell