有没有办法检测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 == 'http:')
  location.href = location.href.replace(/^http:/, 'https:')

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

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

设置的位置。协议导航到一个新的URL。不需要解析/切片任何东西。

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

Firefox 49有一个错误,https可以工作,但https:不能。据说在Firefox 54中已修复。

功能的方式

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

这个怎么样?

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

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