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

当前回答

功能的方式

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

其他回答

试试这个

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

的位置。Href = blah将这个重定向添加到浏览器历史记录中。如果用户点击返回按钮,他们将被重定向回同一页面。最好使用位置。替换,因为它不会将此重定向添加到浏览器历史记录。

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

if (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">

希望有帮助。

这个怎么样?

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

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