我的项目中有很多产品。而且段头是动态的并且可以更新。当更新的时候,我想用301重定向到新的,但我只能用308重定向。代码基本是这样的:
export default async function Page({ params: { slug } }: Props) {
const productData: Promise<Product> = getProduct(slug);
const product = await productData;
if (product.slug !== slug) {
// redirect to the correct slug
permanentRedirect(`/product/${product.slug}`);
}
...
...
}
除此之外,我尝试将其添加到 next.config.js 文件中,但它仍然返回 308。我尝试了客户端重定向,但它仍然无法按我想要的方式工作。
我希望它是301的主要原因是SEO。对于 SEO,人们说 308 还不够,必须使用 301 重定向。
在
next.js
中进行重定向的方法不止一种,但我更喜欢使用 next.config.js
来执行此操作。
以下是如何在
next.config.js
中做到这一点:
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/product/:slug',
destination: async (params) => {
const product = await getProduct(params.slug);
if (product.slug !== params.slug) {
return `/product/${product.slug}`;
}
return null; // No redirection needed
},
permanent: true, // This should ensure a 301 redirect
},
];
},
};
您可以在此处
找到有关此方法的更多信息