首页 文章

检测HTTP或HTTPS,然后在JavaScript中强制使用HTTPS

提问于
浏览
236

有没有办法检测HTTP或HTTPS,然后强制使用HTTPS与JavaScript?

我有一些用于检测HTTP或HTTPS的代码,但我不能强制它使用 https: .

我正在使用window.location.protocol属性来设置网站的所有内容,然后刷新页面以希望重新加载加载到浏览器中的新https'ed URL .

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

9 回答

  • 10

    试试这个

    if (location.protocol != 'https:')
    {
     location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
    }
    
  • 17

    Setting location.protocol navigates to a new URL . 无需解析/切片 .

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

    Firefox 49有一个bug,其中 https 可以工作,但 https: 没有 . 据说是fixed in Firefox 54 .

  • -1

    这不是一个好主意,因为您只是临时将用户重定向到https,浏览器不保存此重定向 .

    您描述了Web服务器的任务(apache,nginx等)http 301, http 302

  • 4

    这个怎么样?

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

    理想情况下,您可以在服务器端执行此操作 .

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

    不是Javascript方式来回答这个问题但是如果您使用CloudFlare,您可以编写page rules,将用户更快地重定向到HTTPS并且它可以使用's free. Looks like this in CloudFlare'页面规则:

    enter image description here

  • 404
    <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>
    
  • -1

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

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

    迎接BrAiNee

  • 36

    我刚刚通过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脚本中添加更多安全性 .

相关问题