HTML 自上而下解析,所以脚本需要放在主页上方;最好的实现方法是服务端或者域名解析的时候做 301 跳转

    1. <script type="text/javascript">
    2. var targetProtocol = "https:";
    3. if (window.location.protocol != targetProtocol)
    4. window.location.href = targetProtocol +
    5. window.location.href.substring(window.location.protocol.length);
    6. </script>
    7. <script type="text/javascript">
    8. var hosts = /^(192.168.1.)/;
    9. if (window.location.hostname !== 'localhost' && !hosts.test(window.location.hostname)) {
    10. // 判断非本地 server http 强制转换成 https
    11. var targetProtocol = "https:";
    12. if (window.location.protocol != targetProtocol)
    13. window.location.href = targetProtocol +
    14. window.location.href.substring(window.location.protocol.length);
    15. }
    16. </script>