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

Nginx 仅重定向通配符服务器块中顶级域的根,nginx,Nginx,我有一个Nginx实例正在运行,在一个公共域下为多个站点提供服务:cloud.example.org。例如,我提供website.cloud.example.org和admin.cloud.example.org 我想将cloud.example.org重定向到website.cloud.example.org。但是只有根/;因此: cloud.example.org-->重定向到website.cloud.example.org cloud.example.org/任何类型的文件或路由-->

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

我想将
cloud.example.org
重定向到
website.cloud.example.org
。但是只有根
/
;因此:

  • cloud.example.org
    -->重定向到
    website.cloud.example.org
  • cloud.example.org/任何类型的文件或路由
    -->未重定向
我的配置如下(我省略了一些不相关的部分,如ssl):

这种配置完全实现了我想要的,但是在我看来,拥有两个相同的
代理
块似乎是一个很大的缺陷。有更好的方法吗

而且,我使用了一个
if
,我知道它并不理想(),所以如果可能的话,我真的想找到另一个解决方案


非常感谢

您可以通过使用两个
server
块来避免
if
语句。为了避免重复代码,请使用
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;
}

我想我可以避免两台服务器阻塞,但是,到目前为止,这似乎是更干净的解决方案
listen 443 ssl http2;
location / {
    proxy_pass         http://my-upstream-server;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}