有没有办法检测HTTP或HTTPS,然后强制使用HTTPS与JavaScript?

我有一些检测HTTP或HTTPS的代码,但我不能强迫它使用HTTPS:。

我使用window.location.protocol属性将站点设置为https:然后刷新页面,希望重新加载加载到浏览器中的新的https'ed URL。

if (window.location.protocol != "https:") {
   window.location.protocol = "https:";
   window.location.reload();
}

当前回答

不是Javascript的方式来回答这个问题,但如果你使用CloudFlare,你可以编写页面规则,重定向用户更快到HTTPS,这是免费的。在CloudFlare的页面规则中是这样的:

其他回答

这不是一个好主意,因为你只是临时重定向用户到https和浏览器不保存这个重定向。

你描述任务的web服务器(apache, nginx等)http 301, http 302

if (location.protocol == 'http:')
  location.href = location.href.replace(/^http:/, 'https:')

你可以:

  <script type="text/javascript">        
        if (window.location.protocol != "https:") {
           window.location.protocol = "https";
        }
    </script>

功能的方式

window.location.protocol === 'http:' && (location.href = location.href.replace(/^http:/, 'https:'));

你应该检查这个: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

将这个元标签添加到index.html内头部

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

希望有帮助。