简体   繁体   English

Nginx:将除一个以外的所有子域都重写为www?

[英]Nginx: rewrite all subdomains to www except for one?

Suppose I have a pair of servers that, due to the way things get deployed, need to use the same nginx.conf . 假设我有一对服务器,由于部署方式不同,因此需要使用相同的nginx.conf One of the servers is at staging.someserver.com , and the other is at www.someserver.com . 其中一台服务器位于staging.someserver.com ,另一台位于www.someserver.com

What I want is a single rewrite line or an if condition that will redirect everything on the domain (mainly www and non-www on http, and non-www on https) to https://www.someserver.com/ , and for http://staging.someserver.com/ to redirect to https://staging.someserver.com/ , but not to https://www.someserver.com/ . 我想要的是一条重写行或if条件,该条件会将域中的所有内容(主要是http上的www和non-www以及https上的non-www)重定向到https://www.someserver.com/ ,并且http://staging.someserver.com/重定向到https://staging.someserver.com/ ,而不重定向到https://www.someserver.com/ How can I do this? 我怎样才能做到这一点?

This is a trick on Nginx configuration : The first server block of HTTP block will be the "default" configuration. 这是Nginx配置上的一个技巧:HTTP块的第一个服务器块将是“默认”配置。

So you can redirect in the first server block everything, and create another server block with your www. 因此,您可以在第一个服务器块中重定向所有内容,并使用www创建另一个服务器块。 configuration ! 配置!

Thats the best solution. 那是最好的解决方案。

I don't know if this is strictly the best way to do this, but I figured something out: 我不知道这是否严格地说是最好的方法,但是我想出了一些办法:

server {
    listen 443 default deferred;

    # ...

    if ($host !~ (staging)|(www).*)
        rewrite ^(.*) https://www.someserver.com$1 permanent;
    }
}

server {
    listen 80;

    # ...

    if ($host !~ staging.*) {                                   
        rewrite ^(.*) https://www.someserver.com$1 permanent;    
    }                                                           
    if ($host ~ staging.*) {                                    
        rewrite ^(.*) https://staging.someserver.com$1 permanent;
    }                                                           
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM