<script>
if (window.location.protocol !== 'https:') {
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
}
</script>以下是用于判断当前访问是否使用 HTTPS,并在不是时自动跳转到 HTTPS 的 JavaScript 代码:
// 判断当前页面是否使用 HTTPS,如果不是则跳转到 HTTPS 版本if (window.location.protocol !== 'https:') {
// 获取当前 URL 并替换协议为 https
var httpsUrl = window.location.href.replace(/^http:/, 'https:');
window.location.replace(httpsUrl);}// 判断当前页面是否使用 HTTPS,如果不是则跳转到 HTTPS 版本// 此版本更健壮,避免了一些边缘情况(function() {
// 检查协议是否为 https
if (window.location.protocol !== 'https:') {
// 构建 HTTPS URL,保留主机名、路径、查询参数和哈希
var httpsUrl = 'https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash;
// 使用 replace 跳转(不会在浏览器历史中留下 HTTP 记录)
window.location.replace(httpsUrl);
}})();1. 放在页面 <head> 中尽早执行:
<!DOCTYPE html><html><head>
<script>
if (window.location.protocol !== 'https:') {
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
} </script>
<!-- 其他 head 内容 --></head><body>
<!-- 页面内容 --></body></html>2. 放在外部 JS 文件中:
// redirect-to-https.js(function() {
if (window.location.protocol !== 'https:') {
var url = 'https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash;
window.location.replace(url);
}})();使用 replace() 而非 href 赋值:避免在浏览器历史中留下 HTTP 页面记录,用户点击返回按钮时不会回到不安全的页面。
尽早执行:将代码放在 <head> 中,*好在所有资源加载之前,减少 HTTP 页面的加载时间。
保留所有路径和参数:确保跳转后用户访问的是同一页面,只是协议不同。
考虑本地开发:如果本地开发使用 http://localhost,你可能需要添加例外情况:
// 跳过 localhost 的强制 HTTPS(开发环境)if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && !window.location.hostname.startsWith('127.')) {
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);}如果使用 服务端配置(如 Nginx、Apache)来做 HTTPS 强制跳转会更好,因为用户不会先加载 HTTP 页面再跳转,性能和安全性都更高。但在某些情况下,前端 JS 方案是必要的补充。