HTML 自上而下解析,所以脚本需要放在主页上方;最好的实现方法是服务端或者域名解析的时候做 301 跳转
<script type="text/javascript">
var targetProtocol = "https:";
if (window.location.protocol != targetProtocol)
window.location.href = targetProtocol +
window.location.href.substring(window.location.protocol.length);
</script>
<script type="text/javascript">
var hosts = /^(192.168.1.)/;
if (window.location.hostname !== 'localhost' && !hosts.test(window.location.hostname)) {
// 判断非本地 server 时 http 强制转换成 https
var targetProtocol = "https:";
if (window.location.protocol != targetProtocol)
window.location.href = targetProtocol +
window.location.href.substring(window.location.protocol.length);
}
</script>