js实现301
使用 window.location 实现 301 重定向
通过修改 window.location.href 或 window.location.replace() 实现页面跳转。虽然这不是真正的服务器端 301 重定向,但可以模拟类似效果。
// 直接跳转(保留历史记录)
window.location.href = "https://new-url.com";
// 替换当前历史记录(更接近 301 效果)
window.location.replace("https://new-url.com");
通过 HTTP 响应实现 301 重定向
纯前端无法直接发送 301 状态码,需配合后端(如 Node.js)实现。以下是示例代码:
Express.js 示例
const express = require('express');
const app = express();
app.get('/old-path', (req, res) => {
res.status(301).redirect('https://new-url.com/new-path');
});
app.listen(3000);
原生 Node.js 示例
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/old-path') {
res.writeHead(301, { 'Location': 'https://new-url.com/new-path' });
res.end();
}
}).listen(3000);
通过 <meta> 标签实现重定向
在 HTML 的 <head> 中添加 <meta> 标签,虽然不是 301,但可用于简单跳转:

<meta http-equiv="refresh" content="0; url=https://new-url.com">
注意事项
- 前端限制:纯 JavaScript 的
window.location或<meta>跳转不会返回 301 状态码,仅适用于客户端跳转。 - SEO 影响:搜索引擎优化的 301 重定向需通过服务器端配置(如 Apache、Nginx 或后端代码)。
- 缓存问题:浏览器可能缓存 301 重定向,测试时需清除缓存。
如需完整的 301 重定向,优先使用服务器配置(如 Nginx 的 return 301 或 Apache 的 Redirect 301)。






