NNext.js 中文网 GitHub

redirects

向 Next.js 应用添加重定向。

重定向使你可以将传入的请求路径重定向到不同的目标路径。

要使用重定向,你可以在 next.config.js 中使用 redirects 键:

next.config.js
module.exports = {
  redirects() {
    return [
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
    ]
  },
}

redirects 可以定义为同步或异步函数。它应返回一个对象数组,或解析为对象数组,这些对象具有 source、destination 和 permanent 属性:

  • source 是传入的请求路径模式。
  • destination 是你想要路由到的路径。
  • permanent 为 true 或 false —— 若为 true 将使用 308 状态码,指示客户端/搜索引擎永久缓存重定向;若为 false 将使用 307 状态码,表示临时重定向且不会被缓存。

为什么 Next.js 使用 307 和 308? 传统上,302 用于临时重定向,301 用于永久重定向,但许多浏览器会将重定向的请求方法改为 GET,而不管原始方法是什么。例如,如果浏览器向 POST /v1/users 发出请求,返回状态码 302 且 location 为 /v2/users,则后续请求可能是 GET /v2/users,而不是预期的 POST /v2/users。Next.js 使用 307 临时重定向和 308 永久重定向状态码,以明确保留所使用的请求方法。

  • basePath:false 或 undefined —— 若为 false,则匹配时不会包含 basePath,只能用于外部重定向。
  • locale:false 或 undefined —— 匹配时是否不应包含区域设置。
  • has 是 has 对象的数组,具有 type、key 和 value 属性。
  • missing 是 missing 对象的数组,具有 type、key 和 value 属性。

重定向会在文件系统(包括页面和 /public 文件)之前检查。

使用 Pages Router 时,重定向不会应用于客户端路由(Link、router.push),除非存在 Proxy 且它与路径匹配。

应用重定向时,请求中提供的任何查询值都会传递到重定向目标。例如,请看以下重定向配置:

js
{
  source: '/old-blog/:path*',
  destination: '/blog/:path*',
  permanent: false
}

小知识:请记住,在 source 和 destination 路径的路径参数中,要在冒号 : 前包含正斜杠 /,否则该路径将被视为字面字符串,你就有可能造成无限重定向。

当请求 /old-blog/post-1?hello=world 时,客户端将被重定向到 /blog/post-1?hello=world。

路径匹配#

允许路径匹配,例如 /old-blog/:slug 将匹配 /old-blog/first-post(不匹配嵌套路径):

next.config.js
module.exports = {
  redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/news/:slug', // 匹配的参数可用于目标路径
        permanent: true,
      },
    ]
  },
}

模式 /old-blog/:slug 匹配 /old-blog/first-post 和 /old-blog/post-1,但不匹配 /old-blog/a/b(不匹配嵌套路径)。模式锚定在开头:/old-blog/:slug 不会匹配 /archive/old-blog/first-post。

你可以对参数使用修饰符:*(零个或多个)、+(一个或多个)、?(零个或一个)。例如,/blog/:slug* 匹配 /blog、/blog/a 和 /blog/a/b/c。

有关更多细节,请阅读 path-to-regexp 文档。

通配符路径匹配#

要匹配通配符路径,可以在参数后使用 *,例如 /blog/:slug* 将匹配 /blog/a/b/c/d/hello-world:

next.config.js
module.exports = {
  redirects() {
    return [
      {
        source: '/blog/:slug*',
        destination: '/news/:slug*', // 匹配的参数可用于目标路径
        permanent: true,
      },
    ]
  },
}

正则表达式路径匹配#

要匹配正则表达式路径,可以将正则表达式包裹在参数后的括号中,例如 /post/:slug(\\d{1,}) 将匹配 /post/123 但不匹配 /post/abc:

next.config.js
module.exports = {
  redirects() {
    return [
      {
        source: '/post/:slug(\\d{1,})',
        destination: '/news/:slug', // 匹配的参数可用于目标路径
        permanent: false,
      },
    ]
  },
}

以下字符 (, ), {, }, :, *, +, ? 用于正则表达式路径匹配,因此当它们在 source 中作为非特殊值使用时,必须通过在它们前面添加 \\ 来进行转义:

next.config.js
module.exports = {
  redirects() {
    return [
      {
        // 这将匹配被请求的 `/english(default)/something`
        source: '/english\\(default\\)/:slug',
        destination: '/en-us/:slug',
        permanent: false,
      },
    ]
  },
}

要仅在标头、cookie 或查询值也匹配 has 字段或不匹配 missing 字段时才匹配重定向,可以使用这些字段。要应用重定向,source 和所有 has 项都必须匹配,且所有 missing 项都必须不匹配。

has 和 missing 项可以具有以下字段:

  • type:String —— 必须是 header、cookie、host 或 query 之一。
  • key:String —— 所选类型中要匹配的键。
  • value:String 或 undefined —— 要检查的值,若为 undefined 则任何值都会匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果将值 first-(?<paramName>.*) 用于 first-second,则可在目标路径中通过 :paramName 使用 second。
next.config.js
module.exports = {
  redirects() {
    return [
      // 如果存在标头 `x-redirect-me`,
      // 将应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'header',
            key: 'x-redirect-me',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果存在标头 `x-do-not-redirect`,
      // 将不会应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        missing: [
          {
            type: 'header',
            key: 'x-do-not-redirect',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果 source、查询和 cookie 都匹配,
      // 将应用此重定向
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // 由于提供了值且未使用命名捕获组(例如 (?<page>home)),
            // page 值将无法在目标路径中使用
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        permanent: false,
        destination: '/another/:path*',
      },
      // 如果存在标头 `x-authorized`
      // 且包含匹配的值,将应用此重定向
      {
        source: '/',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        permanent: false,
        destination: '/home?authorized=:authorized',
      },
      // 如果主机是 `example.com`,
      // 将应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
    ]
  },
}

支持 basePath 的重定向#

在将 basePath 支持与重定向结合使用时,每个 source 和 destination 都会自动加上 basePath 前缀,除非你在重定向中添加 basePath: false:

next.config.js
module.exports = {
  basePath: '/docs',

  redirects() {
    return [
      {
        source: '/with-basePath', // 自动变为 /docs/with-basePath
        destination: '/another', // 自动变为 /docs/another
        permanent: false,
      },
      {
        // 由于设置了 basePath: false,不会添加 /docs
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
        permanent: false,
      },
    ]
  },
}

支持 i18n 的重定向#

在 App Router 中实现带国际化的重定向时,你可以在 next.config.js 的重定向中包含区域设置,但只能是硬编码路径。

对于动态或按请求处理的区域设置,请使用动态路由段和 proxy,它可以根据用户的首选语言进行重定向。

next.config.js
module.exports = {
  redirects() {
    return [
      {
        // 为 App Router 手动处理区域设置前缀
        source: '/en/old-path',
        destination: '/en/new-path',
        permanent: false,
      },
      {
        // 使用参数对所有区域设置进行重定向
        source: '/:locale/old-path',
        destination: '/:locale/new-path',
        permanent: false,
      },
      {
        // 从一个区域设置重定向到另一个
        source: '/de/old-path',
        destination: '/en/new-path',
        permanent: false,
      },
      {
        // 多个区域设置的通配重定向
        source: '/:locale(en|fr|de)/:path*',
        destination: '/:locale/new-section/:path*',
        permanent: false,
      },
    ]
  },
}

在将 i18n 支持与重定向结合使用时,每个 source 和 destination 都会自动添加前缀以处理配置的 locales,除非你在重定向中添加 locale: false。如果使用了 locale: false,你必须为 source 和 destination 添加区域设置前缀,才能正确匹配。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },

  redirects() {
    return [
      {
        source: '/with-locale', // 自动处理所有区域设置
        destination: '/another', // 自动传递区域设置
        permanent: false,
      },
      {
        // 由于设置了 locale: false,不会自动处理区域设置
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
        permanent: false,
      },
      {
        // 由于 `en` 是 defaultLocale,因此这匹配 '/'
        source: '/en',
        destination: '/en/another',
        locale: false,
        permanent: false,
      },
      // 即使设置了 locale: false,也可以匹配所有区域设置
      {
        source: '/:locale/page',
        destination: '/en/newpage',
        permanent: false,
        locale: false,
      },
      {
        // 这会转换为 /(en|fr|de)/(.*),因此不会像 /:path* 那样
        // 匹配顶层 `/` 或 `/fr` 路由
        source: '/(.*)',
        destination: '/another',
        permanent: false,
      },
    ]
  },
}

在极少数情况下,你可能需要为较旧的 HTTP 客户端指定自定义状态码以正确重定向。在这些情况下,你可以使用 statusCode 属性代替 permanent 属性,但不能同时使用两者。为确保 IE11 兼容性,会为 308 状态码自动添加 Refresh 标头。

其他重定向#

版本历史#

版本变更
v13.3.0新增 missing。
v10.2.0新增 has。
v9.5.0新增 redirects。
Next.js 中文网