首页 > 解决方案 > 为共享 Drupal 8 代码库的六个站点中的三个强制 SSL

问题描述

在我的 /sites 文件夹中,我有六个文件夹代表六个不同的 TLD。这些 TLD 中只有三个(tld1.com、tld2.com、tld3.com)具有 SSL 证书。所有六个都在根目录中共享一个 .htaccess 文件。我知道如何为 .htaccess 中的单个 TLD 强制 SSL,但不为三个 TLD 强制。(仅供参考,我在.htaccess 中重写了基础/未注释。)我将不胜感激任何建议/指导。谢谢。

标签: .htaccessdrupal-8

解决方案


这些 TLD 中只有三个(tld1.com、tld2.com、tld3.com)具有 SSL 证书。

这些不是“ TLD ”——它们只是——它们都共享同一个 TLD!

我知道如何为 .htaccess 中的单个 TLD 强制 SSL,但不为三个 TLD

过程非常相似。事实上,如果现有指令特定于您的服务器,您可能需要修改它。(不同的服务器可能需要稍微不同的方法将 HTTP 重定向到 HTTPS,具体取决于它的配置方式。我在下面使用的方法,使用HTTPSserver 变量将是最常见的。)

您只需向RewriteCond现有的 HTTP 到 HTTPS 重定向添加一些条件(指令),以检查所请求的主机名。

例如:

RewriteCond %{HTTPS} !on
RewriteCond %(HTTP_HOST} ^(www\.)?example1\.com [NC,OR]
RewriteCond %(HTTP_HOST} ^(www\.)?example2\.com [NC,OR]
RewriteCond %(HTTP_HOST} ^(www\.)?example3\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

请注意最后一个指令OR上没有标志。RewriteCond

您也可以结合这些条件,因为您只需要检查 3 个域,并且它们似乎都共享相同的 TLD(即。.com)。

RewriteCond %{HTTPS} !on
RewriteCond %(HTTP_HOST} ^(www\.)?(example1|example2|example3)\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

更新:我忘了提到我不希望/不希望“www”成为 URL 的一部分。可以调整您上面共享的代码以完成相同的操作吗?

您可以在上述 HTTP 到 HTTPS 重定向之前将其实现为两个单独的重定向。一个用于您要重定向到 HTTPS 的域,另一个用于其余的域(应该保留在 HTTP 上)。

顺便说一句,所有这些重定向都应该放在您可能拥有的任何现有 Drupal 指令之前。

例如:

# Remove www subdomain from "secure" domains
# Also redirects to HTTPS
RewriteCond %{HTTP_HOST} ^www\.example1\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.example2\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.example3\.com [NC]
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

# Remove www subdomain from other (non-secure) domains
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

# HTTP to HTTPS redirect for "secure" (non-www) domains
RewriteCond %{HTTPS} !on
RewriteCond %(HTTP_HOST} ^example1\.com [NC,OR]
RewriteCond %(HTTP_HOST} ^example2\.com [NC,OR]
RewriteCond %(HTTP_HOST} ^example3\.com [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

前两个规则中的%1反向引用匹配域减去 www 子域。

如果您愿意,可以将上述内容简化为以下内容:

# HTTP to HTTPS and remove www subdomain for secure domains
# Currently assumes all secure domains share the same TLD (ie. ".com")
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %(HTTP_HOST} ^(?:www\.)?(example1|example2|example3)\.com [NC]
RewriteRule ^ https://%1.com%{REQUEST_URI} [R=301,L]

# Remove www subdomain from other (non-secure) domains
RewriteCond %{HTTP_HOST} ^www\.(.+)
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

推荐阅读