js实现301
使用 window.location 实现 301 重定向
在 JavaScript 中可以通过修改 window.location 实现页面跳转,但默认是 302 临时重定向。要模拟 301 永久重定向,通常需要服务器配置,但纯前端可以通过以下方式实现跳转:
window.location.replace("https://example.com/new-url");
replace() 方法不会在历史记录中留下原始页面,行为更接近 301 重定向的效果。
通过 HTTP 响应头实现 301 重定向
真正的 301 重定向需要服务器端配置。以下是常见服务器配置示例:
Node.js Express 示例:
app.get('/old-url', (req, res) => {
res.status(301).redirect('https://example.com/new-url');
});
Apache 服务器 (.htaccess):
Redirect 301 /old-path https://example.com/new-path
Nginx 配置:
server {
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
301 与 302 重定向的区别
- 301 重定向:永久移动,搜索引擎会更新索引
- 302 重定向:临时移动,搜索引擎会保留原地址
注意事项
前端实现的跳转无法真正返回 301 状态码,对 SEO 不友好。重要重定向应始终通过服务器配置实现。
对于单页应用 (SPA),可以使用路由库实现客户端跳转:

// React Router 示例
<Redirect from="/old" to="/new" status={301} />






