Nginx - 仅在主域上强制使用 HTTPS,并在所有子域上强制使用 HTTP

Nginx - 仅在主域上强制使用 HTTPS,并在所有子域上强制使用 HTTP

有一位开发人员尝试为我的 Nginx 服务器创建 SSL 配置,但它仍然无法正常工作。我想强制/重定向我的所有子域到 HTTP,并且只让没有子域的主域使用 SSL。

这是我当前的配置:

set $ssl_rule "";
if ($scheme = http) {
set $ssl_rule "1";
}
if ($scheme = https) {
    set $ssl_rule "0";
}

if ($host = "mystite.com") {
set $ssl_rule "${ssl_rule}1";
}
if ($host = "www.mysite.com") {
    set $ssl_rule "${ssl_rule}1";
}

if ($host ~ (?!www).+.mysite\.com) {
 set $ssl_rule "${ssl_rule}0";
}
if ($ssl_rule = "11") {
 return 301 https://$host$request_uri;
}
#if ($ssl_rule = "00") {
#         return 301 http://$host$request_uri;
#}

有人能看出我的配置有什么问题吗?

答案1

您的主要问题是“如果”将一组域放在一个服务器下,而不是在单独的服务器下定义域。您应该这样做。

# Main domain. Can swap to www if you like.
server {
   server_name example.com;
   listen 443 ssl http2;
   ssl_certificate /var/lib/acme/live/etc;
   ssl_certificate_key /var/lib/acme/live/etc;

   location {
     // whatever
   }
}

# Forward https www to root domain
server {
   server_name www.example.com;
   listen 443 ssl https;
   ssl_certificate /var/lib/acme/live/etc;
   ssl_certificate_key /var/lib/acme/live/etc;

   location / {
     return 301 https://example.com;
   }
}

# Forward www and non-www http to main https
server {
   server_name www.example.com example.com;
   listen 80;

   location / {
     return 301 https://example.com;
   }
}

# First http subdomain
server {
   server_name subdomain2.example.com;
   listen 80;

   location / {
     // whatever
   }
}

# second http subdomain
server {
   server_name subdomain2.example.com;
   listen 80;

   location / {
     // whatever
   }
}

相关内容