仅重定向通配符服务器块中顶级域的根

时间:2019-07-15 10:07:22

标签: nginx

我正在运行一个Nginx实例,该实例在一个公共域cloud.example.org下为多个站点提供服务。例如,我服务website.cloud.example.orgadmin.cloud.example.org

我想将cloud.example.org重定向到website.cloud.example.org。但是根/;所以:

  • cloud.example.org->重定向到website.cloud.example.org
  • cloud.example.org/any_kind_of_file_or_route->未重定向

我的配置如下(我省略了一些无关的部分,例如ssl ):

    server {
        listen 443 ssl http2;

        server_name .cloud.example.org;

        location = / {
            if ($http_host = cloud.example.org) {
                return 301 https://website.cloud.example.org;
            }
            proxy_pass         http://my-upstream-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
        }

        location / {
            proxy_pass         http://my-upstream-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
        }
    }

此配置完全可以实现我想要的功能,但是对我来说,拥有两次相同的proxy块似乎是很不容易的事情。有更好的方法吗?

此外,我使用if,但我知道它并不理想(https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/),所以我真的很想找到其他解决方案

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以通过使用两个if块来避免server语句。为了避免重复代码,请使用include指令,并将公共代码行放入单独的文件中。

例如:

server {
    server_name cloud.example.org;
    location = / {
        return 301 https://website.cloud.example.org;
    }
    include /path/to/common.conf;
}
server {
    server_name .cloud.example.org;
    include /path/to/common.conf;
}

common.conf文件中:

listen 443 ssl http2;
location / {
    proxy_pass         http://my-upstream-server;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}