如何在Next.js中实现旧链接带slug的301重定向?
解决方案
1. 先修复next.config.js的语法错误
你当前的配置里包含无效的nextConfig属性,这是导致报错的直接原因,先把配置修正为:
module.exports = { async redirects() { return []; // 静态重定向无法满足动态slug需求,后续用服务器端逻辑实现 }, };
2. 创建旧路由专属处理页面
在pages/product目录下新建[id].js文件,用来承接旧链接/product/:id的请求,通过服务器端逻辑完成动态301重定向:
import { initializeApollo } from '../your-apollo-init-path'; // 替换成你的Apollo初始化文件路径 import GET_PRODUCTS from '../your-query-path'; // 替换成你的产品查询文件路径 export const getServerSideProps = async (context) => { const { id } = context.params; // 通过ID获取产品数据,提取slug const apolloClient = initializeApollo(context); const { data } = await apolloClient.query({ query: GET_PRODUCTS, variables: { id }, }); const product = data.product; if (!product) { // 产品不存在时返回404 return { notFound: true }; } // 构建新链接并返回301永久重定向(保证SEO) const newUrl = `/product/${product.slug}-${id}`; return { redirect: { destination: newUrl, permanent: true, }, }; }; // 页面无需渲染内容,会直接触发重定向 export default function OldProductPage() { return null; }
3. 保留原有新路由页面
你之前的pages/product/[slugId].js页面保持不变,继续处理新链接/product/:slugId的请求,原有的拆分ID、获取数据逻辑无需修改。
逻辑说明
- 静态重定向无法动态获取产品slug,必须通过服务器端的
getServerSideProps实现动态跳转 - 301永久重定向会告知搜索引擎更新索引,完全满足SEO需求,且浏览器地址栏会自动切换为新的带slug的链接
- 旧路由页面专注处理重定向逻辑,新路由页面负责业务渲染,两者互不干扰
内容的提问来源于stack exchange,提问作者Navro
相关产品推荐
相关产品推荐

