NextJs - 如何重定向到带有 301 状态代码的新 URL?

问题描述 投票:0回答:2

NextJs - 我正在尝试使用以下代码从

/index.html
重定向到
/
URL,

module.exports = {
 async redirects() {
   return [
    {
      source: '/index.html',
      destination: '/',
      permanent: true,
    },
   ]
 },
}

通过参考https://nextjs.org/docs/api-reference/next.config.js/redirects。现在重定向工作正常,但其发送状态代码为

308
但我希望它为
301
。而且它应该对 SEO 友好。

例如:当用户点击 https://www.example.com/index.html 时,它应该重定向到 https://www.example.com,状态为 301。

我该如何解决这个问题?

reactjs redirect next.js seo http-status-code-301
2个回答
1
投票

在 Next.js 中,我们可以列出 next.config.js 文件中的所有重定向。

假设旧路径为/old-page,新路径为/new-page。然后重定向代码将如下编码。

添加属性 permanent: true 将使重定向的状态代码为 301。

next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: '/old-page',
        destination: '/new-page',
        permanent: true,
      },
    ]
  },
}

如果您将查询传递到目标路径,那么 next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: '/old-page/:path*',
        destination: '/new-page/:path*',
        permanent: true,
      },
    ]
  },
}

例如,当请求 /blog1/post-1?user=test 时,用户将被重定向到 /blog/post-1?user=test

路径匹配

如果我们有 slug 或 id 或任何值,我们的 URL 发生变化,我们可以匹配路径并从旧路径重定向到新路径。

例如,如果我们编写了从 /old-blog/:slug 到 /new-blog/:slug 的重定向代码,则 slug 中的更改现在将影响重定向。

这意味着路径 /old-blog/post-1 将重定向到新路径 /new-blog/post-1。

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/new-blog/:slug',
        permanent: true,
      },
    ]
  },
}

官方 Next.js 页面上列出了更多重定向,例如 i18n 支持。您必须参考这里


0
投票

您可以使用状态代码:301,并删除“永久”,请检查此文档 https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props#redirect

© www.soinside.com 2019 - 2024. All rights reserved.