如何将/blog/:id路由重定向至/blog/:slug以兼容旧链接?
实现从
/blog/:id 到 /blog/:slug 的重定向 下面分几种常见技术栈给出具体实现方案:
1. Express(Node.js 后端)
保留原 /blog/:id 路由,在路由处理逻辑中根据文章ID查询对应slug,再返回永久重定向:
app.get('/blog/:id', async (req, res) => { const { id } = req.params; // 从数据库查询对应ID的文章,获取slug const post = await Post.findById(id); if (!post) { return res.status(404).send('文章不存在'); } // 301 永久重定向,对SEO友好 res.redirect(301, `/blog/${post.slug}`); });
2. Next.js
App Router(Next.js 13+)
在 app/blog/[id]/page.js 中编写重定向逻辑:
import { redirect, notFound } from 'next/navigation'; import { getPostById } from '@/lib/posts'; export default async function PostIdPage({ params }) { const post = await getPostById(params.id); if (!post) { notFound(); } // permanent: true 表示301永久重定向 redirect(`/blog/${post.slug}`, 'permanent'); }
Pages Router
在 pages/blog/[id].js 中通过 getServerSideProps 处理重定向:
import { getPostById } from '@/lib/posts'; export async function getServerSideProps(context) { const { id } = context.params; const post = await getPostById(id); if (!post) { return { notFound: true }; } return { redirect: { destination: `/blog/${post.slug}`, permanent: true, }, }; } export default function PostIdPage() { // 不会执行到这里,因为已触发重定向 return null; }
3. Django(Python 后端)
在 urls.py 中添加旧路由,指向专门的重定向视图:
from django.shortcuts import get_object_or_404, redirect from .models import Post def redirect_post_by_id(request, id): post = get_object_or_404(Post, id=id) # permanent=True 对应301永久重定向 return redirect(f'/blog/{post.slug}/', permanent=True) urlpatterns = [ path('blog/<int:id>/', redirect_post_by_id), path('blog/<slug:slug>/', views.post_detail), # 其他路由配置 ]
关键注意事项
- 优先使用301永久重定向:告知搜索引擎更新索引,同时让浏览器、用户书签逐步替换旧链接,避免SEO重复内容问题
- 处理404场景:如果查询不到对应ID的文章,返回404页面,不要随意重定向到首页或其他无关页面
- 静态站点特殊处理:如果是Gatsby、Eleventy这类静态站点,需在构建阶段生成所有旧ID到slug的映射,写入服务器重定向配置文件(比如Netlify的
_redirects):
/blog/1 /blog/my-first-post 301 /blog/2 /blog/second-post 301 # 按此格式列出所有需要重定向的ID与slug对应关系
内容的提问来源于stack exchange,提问作者Andrew Buccellato
相关产品推荐
相关产品推荐

