重定向

重定向功能允许您将传入的请求路径指向不同的目标路径。

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

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

redirects 是一个异步函数,需要返回包含 sourcedestinationpermanent 属性的对象数组:

  • source:传入的请求路径模式
  • destination:要路由到的目标路径
  • permanenttruefalse - 若为 true 将使用 308 状态码,指示客户端/搜索引擎永久缓存此重定向;若为 false 则使用 307 临时状态码且不会被缓存

为何 Next.js 使用 307 和 308? 传统上 302 用于临时重定向,301 用于永久重定向,但许多浏览器会将重定向请求方法改为 GET 而忽略原始方法。例如,浏览器对 POST /v1/users 的请求若返回 302 状态码并指向 /v2/users,后续请求可能会变成 GET /v2/users 而非预期的 POST /v2/users。Next.js 使用 307 临时重定向和 308 永久重定向状态码来明确保留原始请求方法。

  • basePath: falseundefined - 若为 false 则匹配时不包含 basePath,仅适用于外部重定向
  • locale: falseundefined - 匹配时是否排除语言环境
  • has 是由 typekeyvalue 属性构成的 has 对象 数组
  • missing 是由 typekeyvalue 属性构成的 missing 对象 数组

重定向检查优先于文件系统(包括页面和 /public 文件)。

使用页面路由时,除非存在 中间件 且匹配路径,否则重定向不会应用于客户端路由(Linkrouter.push)。

应用重定向时,请求中提供的所有查询参数都会传递到目标地址。例如以下重定向配置:

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

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

路径匹配

支持路径匹配,例如 /old-blog/:slug 会匹配 /old-blog/hello-world(不包含嵌套路径):

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

通配符路径匹配

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

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

正则表达式路径匹配

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

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

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

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

请求头、Cookie 和查询匹配

只有当请求头、Cookie 或查询值同时匹配 has 字段或不匹配 missing 字段时,才会应用重定向。必须同时满足 source 和所有 has 项的匹配,且所有 missing 项均不匹配才会触发重定向。

hasmissing 项可包含以下字段:

  • type: String - 必须是 headercookiehostquery 之一
  • key: String - 要匹配的选定类型的键
  • value: Stringundefined - 要检查的值,若为 undefined 则匹配任意值。可使用类似正则的字符串捕获值的特定部分,例如若对 first-second 使用值 first-(?<paramName>.*),则目标路径中可通过 :paramName 使用 second
next.config.js
module.exports = {
  async redirects() {
    return [
      // 如果存在 `x-redirect-me` 请求头
      // 将应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'header',
            key: 'x-redirect-me',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果存在 `x-dont-redirect` 请求头
      // 将不应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        missing: [
          {
            type: 'header',
            key: 'x-do-not-redirect',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果源路径、查询和 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 支持 使用重定向时,每个 sourcedestination 会自动添加 basePath 前缀,除非您在重定向中设置 basePath: false

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

  async 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 的重定向

当结合 i18n 国际化支持 使用重定向时,每个 sourcedestination 会自动添加配置的 locales 前缀,除非您设置 locale: false。若使用 locale: false 则必须在 sourcedestination 中手动添加语言环境前缀才能正确匹配。

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

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

在极少数情况下,您可能需要为旧版 HTTP 客户端分配自定义状态码以实现正确重定向。此时可以使用 statusCode 属性替代 permanent 属性(但不能同时使用)。为确保 IE11 兼容性,308 状态码会自动添加 Refresh 响应头。

其他重定向方式

版本历史

版本变更
v13.3.0新增 missing 支持
v10.2.0新增 has 支持
v9.5.0新增 redirects 功能

On this page