标签 https 下的文章

在网页head头部加上以下这段代码,如果用户访问了如http://,会被重定向到https://。如果想反过来,即把HTTPS强制重定向到HTTP,把targetProtocol的值改成http就行。

[cce]
<script type="text/javascript">
var targetProtocol = "https:";
if (window.location.protocol != targetProtocol)
 window.location.href = targetProtocol +
  window.location.href.substring(window.location.protocol.length);
</script>
[/cce]

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

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

代码 1(需要修改代码中的 domain.com 为你自己的域名):

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

代码 2 (需要修改代码中的 domain.com 为你自己的域名):

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

代码 3(无需修改):

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

PS:Nginx环境.conf文件,以下二选一

if ($server_port = 80 ) {
return 301 https://$server_name$request_uri;
}
if ($scheme = http ) {
return 301 https://$server_name$request_uri;
}