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

当前回答

下面的代码假设变量'str'包含你的http://....字符串。它检查是否为https,如果为true则不执行任何操作。但是如果是http,它会用https替换http。

if (str.indexOf('https') === -1) { STR = STR .replace('http', 'https') }

其他回答

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

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

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

这个怎么样?

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

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

功能的方式

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

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

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