有没有办法检测HTTP或HTTPS,然后强制使用HTTPS?
我有一些检测HTTP或HTTPS的代码,但我不能强迫它使用https:
。
我正在使用 window.location.protocol 属性将网站设置为https:
,然后刷新页面以希望重新加载加载到浏览器中的新https'ed网址
if (window.location.protocol != "https:") {
window.location.protocol = "https:";
window.location.reload();
}
答案 0 :(得分:424)
试试这个
if (location.protocol != 'https:')
{
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
答案 1 :(得分:43)
Setting location.protocol navigates to a new URL。无需解析/切片。
if (location.protocol !== "https:") {
location.protocol = "https:";
}
Firefox 49有一个bug,其中https
有效但https:
没有。据说是fixed in Firefox 54。
答案 2 :(得分:18)
这不是一个好主意,因为您只是临时将用户重定向到https,浏览器不会保存此重定向。
您描述了web-server(apache,nginx等)http 301, http 302
的任务答案 3 :(得分:13)
这个怎么样?
if (window.location.protocol !== 'https:') {
window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}
但理想情况下,您可以在服务器端执行此操作。
答案 4 :(得分:11)
if (location.protocol == 'http:')
location.href = location.href.replace(/^http:/, 'https:')
答案 5 :(得分:4)
不是Javascript方式来回答这个问题但是如果您使用CloudFlare,您可以编写page rules,将用户更快地重定向到HTTPS并且它是免费的。在CloudFlare的页面规则中看起来像这样:
答案 6 :(得分:4)
将此元标签添加到您的index.html 头部
中<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
希望有帮助。
答案 7 :(得分:0)
功能方式
window.location.protocol === 'http:' && (location.href = location.href.replace(/^http:/, 'https:'));
答案 8 :(得分:0)
您可以这样做:
<script type="text/javascript">
if (window.location.protocol != "https:") {
window.location.protocol = "https";
}
</script>
答案 9 :(得分:0)
我喜欢这个问题的答案。但是要想发挥创造力,我想再分享一种方式:
<script>if (document.URL.substring(0,5) == "http:") {
window.location.replace('https:' + document.URL.substring(5));
}
</script>
答案 10 :(得分:0)
下面的代码假定变量'str'包含您的http:// ....字符串。它检查是否为https,如果为true,则不执行任何操作。但是,如果是http,它将用https替换http。
<init>()
答案 11 :(得分:-1)
<script type="text/javascript">
function showProtocall() {
if (window.location.protocol != "https") {
window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
window.location.reload();
}
}
showProtocall();
</script>
答案 12 :(得分:-1)
您好我使用此解决方案完美无缺。无需检查,只需使用https。
C:\Program Files\Java\jdk1.8.0_101\bin
迎接BrAiNee
答案 13 :(得分:-2)
我刚刚通过Pui Cdm测试了所有脚本变体,包括上面的答案和许多其他使用php,htaccess,服务器配置和Javascript,结果是脚本
<script type="text/javascript">
function showProtocall() {
if (window.location.protocol != "https") {
window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
window.location.reload();
}
}
showProtocall();
</script>
由vivek-srivastava提供 效果最好,您可以在java脚本中添加更多安全性。