rewrite/redirect http:// 和 http://www 到 https:// 使用 htaccess

rewrite/redirect http:// and http://www to https:// using htaccess

我是编辑 htaccess 文件的新手。我想做的是: rewrite/redirect 个特定子域,例如 subdomain1、subdomain2 等来自:

https://www.subdomain.example.com
http://www.subdomain.example.com
http://subdomain.example.com

收件人:

https://subdomain.example.com

我根据其他问题拼凑了以下代码,但它似乎不起作用。 任何人都可以解释我做错了什么并帮助我修复代码。

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} ^80$
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

您可以使用以下内容:

RewriteEngine on

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R,L]

这会将所有子域从 http://www 重定向到 https://

对于 subdomain.example.com 您可以使用以下内容:

RewriteEngine on

RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com [NC]
 RewriteRule ^ https://subdomain.example.com%{REQUEST_URI} [R,L]

仅规范化(“重定向”)特定子域 ...

https://www.subdomain.example.com
http://www.subdomain.example.com
http://subdomain.example.com

To:

https://subdomain.example.com

您需要在 .htaccess 文件的顶部附近执行类似这样的操作:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(subdomain\.example\.com) [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

第三个条件确保它只适用于特定的子域。

要使其适用于多个子域(假设 no-www 对所有子域都是规范的),那么您可以仅修改第三个条件以识别它应适用的子域。例如:

RewriteCond %{HTTP_HOST} ^(?:www\.)?((?:subdomain1|subdomain2|subdomain3)\.example\.com) [NC]

使用 302(临时)重定向进行测试以避免潜在的缓存问题。测试前您需要清除浏览器缓存。


RewriteCond %{HTTPS} !on
RewriteCond %{SERVER_PORT} ^80$
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

这是正确的,但它无法针对 HTTPS 或 www 子域。另外,检查 %{HTTPS} !on%{SERVER_PORT} ^80$ 真的是一回事。