.htaccess 通用格式的 http 重定向到 https,具有所有子域限制

.htaccess general format of http redirect to https with all subdomains restriction

我到处都看到许多关于如何从 http 重定向到 https 的指南,但只有少数是通用的域名 + NONE 其中试图避免 "subdomain scaming" 的情况。使用 "subdomain scaming" 我的意思是当有人试图访问网站 www.example.com 上的 www.fdasfsdafa.example.com 时。我希望这会重定向到 https://www.example.com。我需要一些带有域名代码变量的一般示例。为什么?因为我有多个域多站点!非常感谢您的帮助!我花了几个小时在谷歌上搜索这个,但没有任何可用的例子。

这是我当前的代码。它工作得很好,但不处理子域重定向到 https 主域。子域基本上打开 http 站点 = 不安全的网站。

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
</IfModule>

您可以使用:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# subdomains restriction -> https www.domain
RewriteCond %{HTTP_HOST} !^(www\.)?[^.]+\.[^.]+$ [NC]
RewriteCond %{HTTP_HOST} ^.+\.([^.]+\.[^.]+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]

# http -> https www.domain
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

</IfModule>