Redirect Nginx将所有[http/www/https www]重定向到[https非www]

Redirect Nginx将所有[http/www/https www]重定向到[https非www],redirect,nginx,Redirect,Nginx,我希望在https上访问以下服务器名称: example.com test.example.com api.example.com api.test.example.com # And I might add more, all on example.com of course # ... 我想重定向所有http,http://www和https://www至https://non-www 比如: 查看我在网上找到的一个简单示例,我尝试了以下方法: server { listen 8

我希望在https上访问以下服务器名称:

example.com
test.example.com
api.example.com
api.test.example.com

# And I might add more, all on example.com of course
# ...
我想重定向所有
http
http://www
https://www
https://non-www

比如:

查看我在网上找到的一个简单示例,我尝试了以下方法:

server {
    listen 80;
    server_name example.com test.example.com www.example.com www.test.example.com api.example.com api.test.example.com www.api.example.com www.api.test.example.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443;
    server_name www.example.com www.test.example.com www.api.example.com www.api.test.example.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443;
    server_name example.com test.example.com api.example.com api.test.example.com;
    # 
    # The rest of the config that that follows is indeed for the names
    # that I want to redirect everything to
    # ...
}
我认为
$host
指的是
/
之前的url部分,没有
www
。 比如,如果我访问
www.api.test.example.com
,那么$host将是
api.test.example.com
。等等


但是,在注意到它的行为方式并检查Nginx变量之后,我似乎认为我错了。虽然它没有很清楚地解释,也没有提供示例,也没有说明在没有www的情况下获取完整域(包括子域)要使用什么变量。

有多种方法可以做到这一点,但是如果此服务器只处理
example.com
的子域,您可以通过使用正则表达式和默认服务器来简化,而不是为
server\u name
指令指定长列表

例如:

server {
    listen 80;
    listen 443 ssl;

    server_name ~^www\.(?<domain>.+)$;

    return 301 https://$domain$request_uri;        
}

server {
    listen 80 default_server;
    return 301 https://$host$request_uri;        
}

server {
    listen 443 ssl default_server;
    ...
}
服务器{
听80;
听443ssl;
服务器名称^ www.(?.+)$;
返回301 https://$domain$request\u uri;
}
服务器{
监听80个默认_服务器;
返回301 https://$host$request\u uri;
}
服务器{
侦听443 ssl默认_服务器;
...
}
第一个
服务器
块仅匹配以
www.
开头的主机名。第二个服务器块使用
http
匹配其他所有内容。第三个
server
块使用
https
匹配其他所有内容


假定此服务器具有一个通配符证书,该证书对所有子域都是通用的。有关详细信息,请参阅。

谢谢!工作起来很有魅力!如果我将您的
return301…
包装在
location/{}
块中,可以吗?因为我还需要在重定向之前添加另一个位置:
root/var/www/letsencrypt;location/.well-known/acme challenge/{default_type“text/plain”;try_files$uri=404;}
我的意思是我已经尝试过(两个服务器块中的每一个都是一样的)并且它工作正常。我只是不确定是否可以重复我自己(我在重定向之前在两个服务器块中都添加了它)哦,我没有通配符证书。但我可以在添加新子域时简单地重新生成我的证书(这种情况并不经常发生,按照我设置Docker的方式,我运行一个脚本,不到一分钟的时间——当然,我现在只有几个子域,也许100子域不会那么快,但仍然在脚本中)。我会定期检查让我们加密,他们很快就会提供通配符(如果还没有的话)是的。事实上,如果你想添加更多的位置,你必须在默认位置块中包装退货。太棒了!这里是Nginx newb,但我喜欢它!谢谢!
server {
    listen 80;
    listen 443 ssl;

    server_name ~^www\.(?<domain>.+)$;

    return 301 https://$domain$request_uri;        
}

server {
    listen 80 default_server;
    return 301 https://$host$request_uri;        
}

server {
    listen 443 ssl default_server;
    ...
}