首页 > 解决方案 > Redirect only HTTP subdomain to HTTPS subdomain in htaccess

问题描述

How do you redirect only the HTTP subdomain to HTTPS subdomain in .htaccess? The main site is in WordPress and already redirected to HTTPS with a plugin, but the subdomain is a PHP created site. I have looked and not seen a conclusive solution to this on here.

I copy and pasted this suggested code but it did nothing:

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

标签: apache.htaccessredirectmod-rewrite

解决方案


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

这将创建一个重定向循环(如果执行的话)。为了从 HTTP 重定向到 HTTPS,您需要首先检查您尚未使用 HTTPS(否则您将获得重定向循环)。

这些指令需要.htaccess放在子域的文档根目录中。或者,如果子域指向主站点的文档根目录,则位于根 (WordPress)文件的顶部。.htaccess重要的是重定向必须WordPress 前端控制器之前进行。

这还假设您的 SSL 证书直接安装在您的应用程序服务器上,而不是代理服务器上。

尝试以下操作:

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

这将检查HTTPS不包含“on”并且在重定向到同一主机上的 HTTPS 之前正在请求子域。

尽管如果 WP 只是简单地重定向主域,那么您可以在其中执行所有这些操作.htaccess并简单地删除检查HTTP_HOST. 尽管如果您有其他不应重定向到 HTTPS 的子域,则更改CondPattern以仅匹配子域或主域(和 www 子域)。例如:

RewriteCond %{HTTP_HOST} ^((subdomain|www)\.)?example\.com [NC]

推荐阅读