js实现301重定向
使用 window.location.replace 方法
通过 window.location.replace 方法可以实现301重定向的效果。该方法不会在浏览器的历史记录中留下痕迹,用户无法通过返回按钮回到原始页面。
window.location.replace("https://example.com/new-url");
使用 window.location.href 方法
window.location.href 方法也可以实现页面重定向,但会在浏览器的历史记录中留下痕迹,用户可以通过返回按钮回到原始页面。虽然效果类似,但严格来说并不是301重定向。
window.location.href = "https://example.com/new-url";
使用服务器端重定向(推荐)
对于真正的301重定向,推荐在服务器端配置。以下是几种常见服务器环境的配置方法:
Apache 服务器
在 .htaccess 文件中添加以下代码:
Redirect 301 /old-url https://example.com/new-url
Nginx 服务器
在 Nginx 配置文件中添加以下代码:
server {
listen 80;
server_name example.com;
return 301 https://example.com/new-url$request_uri;
}
Node.js 服务器
使用 Express 框架时,可以通过以下代码实现301重定向:
app.get('/old-url', (req, res) => {
res.redirect(301, '/new-url');
});
使用 <meta> 标签重定向
虽然不推荐用于301重定向,但可以通过 <meta> 标签实现页面跳转。这种方法通常用于客户端重定向,但搜索引擎可能不会将其识别为301重定向。

<meta http-equiv="refresh" content="0; url=https://example.com/new-url">
注意事项
- 客户端重定向(如 JavaScript 或
<meta>标签)可能不会被搜索引擎识别为301重定向,影响 SEO。 - 服务器端重定向是更可靠的方法,能够确保搜索引擎正确更新索引。
- 确保重定向目标 URL 是绝对路径,避免相对路径导致的错误。






