前端如何重定向

重定向有多种实现方式,选择哪种取决于你的具体需求和场景:

1. 服务器端重定向(推荐)

HTTP 状态码重定向

复制代码
// Node.js/Express
app.get('/old-url', (req, res) => {
  res.redirect(301, '/new-url'); // 301 永久重定向
  // 或
  res.redirect(302, '/new-url'); // 302 临时重定向
});

// PHP
header('Location: /new-url', true, 301);
exit();

// Apache (.htaccess)
Redirect 301 /old-url /new-url

状态码说明

  • 301 Moved Permanently:永久重定向(SEO友好)

  • 302 Found:临时重定向

  • 307 Temporary Redirect:临时重定向(保持请求方法)

  • 308 Permanent Redirect:永久重定向(保持请求方法)


2. 客户端 JavaScript 重定向

常用方法

复制代码
// 方法1:最常用(会在历史记录中留下记录)
window.location.href = 'https://example.com/new-url';

// 方法2:替换当前历史记录(用户不能返回)
window.location.replace('https://example.com/new-url');

// 方法3:assign() 方法
window.location.assign('https://example.com/new-url');

带延迟的重定向

复制代码
// 3秒后重定向
setTimeout(() => {
  window.location.href = '/new-page';
}, 3000);

条件重定向

复制代码
// 基于某些条件重定向
if (userLoggedIn) {
  window.location.href = '/dashboard';
} else {
  window.location.href = '/login';
}

3. HTML 元标签重定向

复制代码
<!-- 5秒后重定向 -->
<meta http-equiv="refresh" content="5; url=https://example.com/new-page">

4. 框架特定的重定向

React Router

复制代码
import { useNavigate, Navigate } from 'react-router-dom';

// 方式1:在组件中使用
function MyComponent() {
  const navigate = useNavigate();
  
  useEffect(() => {
    navigate('/new-route');
  }, []);
  
  return <div>重定向中...</div>;
}

// 方式2:使用 Navigate 组件
function RedirectComponent() {
  return <Navigate to="/new-route" replace />;
}

Vue Router

复制代码
// 在组件方法中
this.$router.push('/new-route');
// 或
this.$router.replace('/new-route'); // 不记录历史

// 在路由守卫中
router.beforeEach((to, from, next) => {
  if (to.path === '/restricted') {
    next('/login');
  } else {
    next();
  }
});

5. 选择指南

何时使用服务器端重定向

  • ✅ SEO 优化(搜索引擎会更新索引)

  • ✅ 性能更好(减少客户端处理)

  • ✅ HTTP 到 HTTPS 重定向

  • ✅ 域名变更或 URL 结构更改

何时使用客户端重定向

  • ✅ 需要条件逻辑(根据用户状态决定)

  • ✅ 单页应用(SPA)内部导航

  • ✅ 表单提交后的跳转

  • ✅ 需要用户交互后的跳转

何时使用 HTML 元重定向

  • ✅ 简单的静态页面重定向

  • ✅ 维护页面或建设中的跳转


6. 最佳实践示例

完整的条件重定向

复制代码
// 检查用户认证状态并重定向
function checkAuthAndRedirect() {
  const isAuthenticated = checkUserAuth();
  const currentPath = window.location.pathname;
  
  if (!isAuthenticated && currentPath !== '/login') {
    // 未登录且不在登录页,重定向到登录页
    window.location.replace('/login?redirect=' + encodeURIComponent(currentPath));
  } else if (isAuthenticated && currentPath === '/login') {
    // 已登录但在登录页,重定向到首页或目标页
    const redirectTo = new URLSearchParams(window.location.search).get('redirect');
    window.location.href = redirectTo || '/dashboard';
  }
}

安全的开放重定向防护

复制代码
// 避免开放重定向漏洞
function safeRedirect(url) {
  const allowedDomains = ['example.com', 'trusted-site.com'];
  const targetHostname = new URL(url, window.location.origin).hostname;
  
  if (allowedDomains.includes(targetHostname) || targetHostname === window.location.hostname) {
    window.location.href = url;
  } else {
    // 不允许的重定向,跳转到安全页面
    window.location.href = '/error?message=invalid_redirect';
  }
}

总结推荐

  • 首选服务器端重定向(特别是 301),对 SEO 友好

  • SPA 内部使用框架路由(React Router/Vue Router)

  • 条件跳转使用 JavaScript (window.location.replace())

  • 避免开放重定向漏洞,始终验证目标 URL

根据你的具体技术栈和需求选择合适的重定向方式。

相关推荐
大龄秃头程序员14 分钟前
iOS Method Swizzling 的工程化实践:如何处理多重交换与第三方冲突
前端
liangshanbo121518 分钟前
Webpack 文件指纹面试题整理
前端·webpack·node.js
xieter27 分钟前
【技术精选】Node.js 核心事件循环机制与异步 I/O 深度剖析 (2026-10-02)
前端·javascript
计算机魔术师1 小时前
Ethan Mollick 谈点与群:智能体自组织为何让管理假设失效
前端
故七月2 小时前
GEO 信源评估体系:如何判断一条网页信源能否被大模型采信
前端·网络·人工智能
liangshanbo12152 小时前
Webpack 常见 Plugin 面试题
前端·webpack·node.js
xxwl5852 小时前
vue3的入门学习
前端·vue.js·学习
用户847172102842 小时前
.shot 文件格式规范
前端·后端
web打印社区2 小时前
政务办事大厅:叫号小票、办理回执网页怎么静默出纸
前端·javascript·vue.js·pdf·html·政务
C++ 老炮儿的技术栈2 小时前
有符号变量与无符号变量的区别
服务器·开发语言·前端·数据结构·c++·算法·c