前言

上回说到,kangle EASYPANEL虚拟主机设置伪静态的方法,想必看了文章的各位已经实现了,今天呢柠檬茶教给大家,如何从HTTP强制跳转到HTTPS。

HTTP 80 强制转 HTTPS

全站采用https协议访问,就需要http重定向到https,只需要在.htaccess加入下面规则

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]

或者

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]

强制301重定向 HTTPS

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L]
</IfModule>

高级用法

RewriteEngine on

强制HTTPS

RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80

某些页面强制

RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

强制HTTP

RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443

某些页面强制

RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

apache mod_rewrite实现HTTP和HTTPS重定向跳转

当你的站点使用了HTTPS之后,你可能会想把所有的HTTP请求(即端口80的请求),全部都重定向至HTTPS(即端口443)。这时候你可以用以下的方式来做到:(Apache mod_rewrite)

把这段代码放在.htaccess文件,即可实现HTTP到HTTPS的重定向。

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{SERVER_PORT} 80
 RewriteRule ^(.*)$ https://blog.mimvp.com/$1 [R=301,L]
</IfModule>

而当你又想用回HTTP的时候,反过来就可以了:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{SERVER_PORT} 443
 RewriteRule ^(.*)$ https://blog.mimvp.com/$1 [R=301,L]
</IfModule>

其中R=301表示Moved Permanently,即告诉搜索引擎或者浏览器下去直接访问后者的地址,

如果只是试验性地重定向,可以使用R=302(Found),临时跳转

Last modification:March 15, 2020
如果觉得我的文章对你有用,请随意赞赏