js实现301重定向
使用 window.location 实现重定向
通过修改 window.location 对象的 href 属性,可以实现页面重定向。虽然这种方式不是严格的 301 重定向(属于客户端跳转),但在某些场景下可以模拟效果。
window.location.href = "https://example.com/new-page";
使用 window.location.replace 实现无历史记录重定向
window.location.replace 方法会替换当前页面,且不会在浏览历史中留下记录,更接近 301 重定向的效果。
window.location.replace("https://example.com/new-page");
通过服务器端配置实现 301 重定向
真正的 301 重定向需要在服务器端配置。以下是常见服务器环境下的配置方法:

Apache 服务器
在 .htaccess 文件中添加以下规则:
Redirect 301 /old-page https://example.com/new-page
Nginx 服务器
在 Nginx 配置文件中添加以下规则:

server {
listen 80;
server_name example.com;
return 301 https://example.com/new-page;
}
Node.js 服务器
在 Express 应用中,可以使用 res.redirect 方法实现 301 重定向:
app.get('/old-page', (req, res) => {
res.redirect(301, '/new-page');
});
使用 HTML <meta> 标签实现重定向
虽然这不是 301 重定向,但可以通过 HTML 的 <meta> 标签实现页面跳转:
<meta http-equiv="refresh" content="0; url=https://example.com/new-page">
注意事项
- 客户端重定向(JavaScript 或
<meta>)无法返回 301 状态码,仅适用于前端跳转需求。 - 搜索引擎优化(SEO)建议使用服务器端 301 重定向,以确保传递页面权重。
- 避免在单页应用(SPA)中滥用客户端重定向,可能导致不良用户体验。






