【问题标题】:Conditional Redirects in NextJSNextJS 中的条件重定向
【发布时间】:2021-10-31 06:06:09
【问题描述】:

上下文:我有一个博客,其中包含大量被 Google 索引的内容。例如,所有内容都被索引为www.site.com/post1。我正在将我的博客迁移到 NextJS,并且我已将博客文章的范围限定为 www.site.com/blog/post1。我能够轻松地使用 301 重定向来维护这些博客文章的 SEO。但是,我遇到了一个问题,像www.site.com/sitemap.xml 这样的链接也被重定向到www.site.com/blog/sitemap.xml。只有当模式与某些路径不匹配时,有没有办法重定向?这是我在 next.config.js 中关于重定向的部分

async redirects() {
    return [
      {
        source: '/:slug',
        destination: '/blog/:slug',
        permanent: true// Matched parameters can be used in the destination
      },
      {
        source: '/sitemap.xml',
        destination: '/sitemap.xml',
        permanent: false// Matched parameters can be used in the destination
      }
    ]
  }

【问题讨论】:

    标签: reactjs react-router next.js nextjs-dynamic-routing


    【解决方案1】:

    我认为顺序很重要,您是否尝试过将站点地图规则放在首位?

    async redirects() {
        return [
          {
            source: '/sitemap.xml',
            destination: '/sitemap.xml',
            permanent: false// Matched parameters can be used in the destination
          },
          {
            source: '/:slug',
            destination: '/blog/:slug',
            permanent: true// Matched parameters can be used in the destination
          }
        ]
      }
    

    否则,可能需要使用正则表达式

    async redirects() {
        return [
          {
            source: `/:slug(^((?!sitemap\.xml).)*$)`,
            destination: '/blog/:slug',
            permanent: true// Matched parameters can be used in the destination
          },
          {
            source: '/sitemap.xml',
            destination: '/sitemap.xml',
            permanent: false// Matched parameters can be used in the destination
          }
        ]
      }
    

    【讨论】:

    • 我尝试订购它们似乎没有帮助,但会尝试您提到的第二个选项
    猜你喜欢
    • 2020-12-09
    • 2022-06-12
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2012-02-04
    • 2012-01-09
    相关资源
    最近更新 更多