nginx 将子域重写为子域

nginx rewrite for subsubdomains to subdomains

我们有一个应用程序,我们在其中为每个客户的安装使用子域。所以我们有 customer1.ourapp.com、customer2.ourapp.com、customer3.ourapp.com 等等。

出于安全考虑,我们希望将所有 http 重定向到 https,因为我们有通配符 SSL 证书。 此外,一些客户并不精通技术并将 www 添加到他们的域名中,因此您会得到类似这样的内容:http://www.customer1.ourapp.com or https://www.customer1.ourapp.com。在这些情况下,SSL 证书因子域而无效。

我正在尝试为 nginx 编写 vhost 配置以在这两种情况下进行正确的重定向。我得到了 http 到 https 的重定向来使用:

server {
    listen      80;
    server_name *.ourapp.com;

     #Rewrite all nonssl requests to ssl.
     return 301 https://$host$request_uri$is_args$args;
}

正确使用 url:

server {
    listen      443;
    server_name *.ourapp.com;

     #Rest of config
}

尝试了 subsub 域,但不匹配:

server {
        server_name "~^(.*)\.(.*)\.ourapp\.com$";
        return 301 https://.ourapp.com$request_uri;
}

知道如何让它工作吗?

通配符服务器优先于正则表达式服务器并且也匹配 'www...'。 您可以对这两种情况使用一个定义:

server_name ~ ^(?:.*\.)?(.*)\.ourapp\.com$;
return 301 https://.ourapp.com$request_uri;