js实现重定向
使用 window.location 实现重定向
通过修改 window.location 对象的属性可以实现页面重定向。
// 直接修改 href
window.location.href = "https://example.com";
// 使用 assign 方法(可回退)
window.location.assign("https://example.com");
// 使用 replace 方法(不可回退)
window.location.replace("https://example.com");
href和assign:浏览器会记录跳转前的页面,用户可通过后退按钮返回。replace:替换当前历史记录,无法通过后退返回原页面。
使用 meta 标签实现重定向
在 HTML 的 <head> 中添加 <meta> 标签,通过 http-equiv="refresh" 实现自动跳转。
<meta http-equiv="refresh" content="3; url=https://example.com">
content="3"表示 3 秒后跳转。- 适用于无需 JavaScript 的场景,如静态页面。
使用 HTTP 状态码重定向
在服务器端(如 Node.js)通过设置 302 或 301 状态码实现重定向。
// Node.js Express 示例
const express = require("express");
const app = express();
app.get("/old-page", (req, res) => {
res.redirect(301, "https://example.com/new-page");
});
app.listen(3000);
301:永久重定向,搜索引擎会更新链接。302:临时重定向,搜索引擎不会更新链接。
使用 history.pushState 或 replaceState
适用于单页应用(SPA),仅修改浏览器历史记录而不刷新页面。
// 添加新历史记录
window.history.pushState({}, "", "/new-url");
// 替换当前历史记录
window.history.replaceState({}, "", "/new-url");
- 需配合前端路由框架(如 React Router、Vue Router)使用。
- 不会向服务器发送请求,仅改变 URL。
注意事项
- 避免滥用重定向,尤其是
meta自动跳转,可能被搜索引擎视为作弊。 - 确保目标 URL 有效,否则可能导致循环重定向。
- 在单页应用中优先使用路由跳转,而非全局重定向。







