有没有办法检测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();
}

当前回答

嗨,我用这个解决方案工作完美。不需要检查,只需使用https。

<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>

其他回答

这个怎么样?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

不过,理想情况下,您应该在服务器端进行此操作。

你应该检查这个: 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">

希望有帮助。

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

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

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

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