如果已经购买并配置好了 SSL 证书,想要将 http 直接重定向到 https 访问,可以用 Apache 的 .htaccess 文件来设置,具体代码如下:

找不到.htaccess文件请参考:https://help.laoxuehost.com/control-panel/cpanel/createhtaccessfile.html

只需要将以下代码放到 .htaccess 文件中即可,如果 .htaccess 文件中已经有内容,请将重定向代码放在最前面。

RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

高级进阶

以上规则会影响子域名,如果希望只有主域名使用https,而子域名不使用,使用以下规则:

RewriteEngine On
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTP_HOST} !^www.laoxuehosts.com
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

注意上面的规则中的laoxuehosts.com换成你的域名。

如果只想排除某个子域名,也就是只有某个子域名不使用https,可以使用以下规则:

RewriteEngine On
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{REQUEST_URI} !^https://help.laoxuehosts.com
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

注意上面的规则中的help.laoxuehosts.com换成你的域名。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。