.htaccess 重定向规则到 www 和 htpps 但排除子域

.htaccess redirect rules to www and htpps but to exclude subdomain

在阅读了此处有关 .htaccess 和重定向的所有相关答案以及对 .htaccess 重写条件和规则的一些实验后,我的问题仍然存在。

我设法为我的 Magento 站点强制使用 www 和 https。这是我目前拥有的:

RewriteCond %{HTTPS} off
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

在创建子域 test.example.compublic_html/test/ 的测试环境后,我想将其排除在上述规则之外,因为子域既没有 www 也没有 https。

我试图将此例外情况放入上述规则中,但没有成功。

RewriteCond %{HTTP_HOST} !^test\.example\.com$

例如,当我键入 http://test.example.com/admin/ 进入 Magento 管理员时,它会将我重定向到 https://www.example.com/admin/ 我还必须编辑 public_html/test/.htaccess file 吗?

提前致谢

是的,这是因为您的规则,第二条规则检查主机值是否不以 www 开头并将主机重定向到 www.example.com 此规则还将任何非 www http 主机重定向到带有 www.

的主域

要解决此问题,您可以使用单个规则将 http 重定向到 https:www,不包括子域

RewriteEngine on

RewriteCond %{HTTP_HOST} !^test\.example\.com$
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]