.htaccess HTTP 或 HTTPS 取决于子域级别

.htaccess HTTP or HTTPS depending on subdomain level

我买不起无限级别子域的通配符 SSL 证书,我只有 *.domain.tld 通配符。所以我想把 HTTPS 请求重写成 HTTP 请求 如果 %{HTTP_HOST} 变量中有不止一级的子域。如果有 none 或 1 个子域,HTTP 请求应重写为 HTTPS 请求。

例如:

www.domain.tld       -> 1 subdomain(s) HTTPS
domain.tld           -> 0 subdomain(s) HTTPS
sub.domain.tld       -> 1 subdomain(s) HTTPS
two.sub.domains.tld  -> 2 subdomain(s) HTTP
a.b.c.domain.tld     -> 3 subdomain(s) HTTP

这是我能想到的唯一不涉及我购买通配符证书的解决方案。

您可以使用:

RewriteEngine on

# redirect http to https with 0 or 1 subdomain
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([^.]+\.){1,2}[^.]+$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301] 

# redirect https to http with 2 or more subdomains
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^([^.]+\.){3,}[^.]+$ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301] 

您无法避免使用 https 到 http 重定向的 SSL 安全错误消息