如何使用JavaScript实现通配符全站重定向
核心问题原因
你遇到的问题是两个原因共同导致的:
- 服务器未配置全路径回退规则,访问
rootdomain.com/path时没有加载到写了重定向逻辑的index.html,代码根本没有执行 - 第一版代码存在语法错误,URL拼接时多写了多余的加号导致跳转地址异常
解决步骤
第一步:修正服务器配置
默认只有访问根路径时才会加载根目录的index.html,要让所有路径的请求都加载该文件,需要调整Web服务器配置:
- Nginx:在server配置块中添加
try_files $uri $uri/ /index.html; - Apache:在.htaccess中添加重写规则,将所有非静态文件请求指向根目录index.html
- 托管平台:如果用Vercel、Netlify等平台,需要配置重写规则将所有路径请求指向/index.html
第二步:修正JS代码逻辑
推荐直接替换当前URL的源站地址,不需要手动拼接路径,能完整保留原URL的路径、查询参数、哈希值,兼容性更好:
倒计时跳转修复版
<script> setInterval(function(){ let number = document.getElementById("number").innerHTML; const targetSite = 'https://test.example.com'; if (number > 0) { number--; } document.getElementById("number").innerHTML = number; if (number == 0) { window.location.replace(window.location.href.replace(window.location.origin, targetSite)); } }, 1000); </script>
延迟5秒跳转修复版
<script> window.setTimeout(function(){ const targetSite = 'https://test.example.com'; window.location.href = window.location.href.replace(window.location.origin, targetSite); }, 5000); </script> <h1>Wait 5seconds</h1>
内容的提问来源于stack exchange,提问作者Winie
相关产品推荐
相关产品推荐

