Menu

redirects

重定向允许你将传入的请求路径重定向到不同的目标路径。

要使用重定向,你可以在 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 永久重定向状态码来明确保留使用的请求方法。

  • basePathfalseundefined - 如果为 false,匹配时不会包含 basePath,只能用于外部重定向。
  • localefalseundefined - 匹配时是否不应包含语言环境。
  • has 是一个 has 对象数组,具有 typekeyvalue 属性。
  • missing 是一个 missing 对象数组,具有 typekeyvalue 属性。

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

使用 Pages Router 时,重定向不会应用于客户端路由(Linkrouter.push),除非存在 Proxy 并匹配该路径。

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

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

值得注意的是:记得在 sourcedestination 路径的路径参数中,在冒号 : 之前包含正斜杠 /,否则路径将被视为字面字符串,你可能会导致无限重定向。

当请求 /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,
      },
    ]
  },
}

Header、Cookie 和 Query 匹配

要仅在 header、cookie 或 query 值也匹配 has 字段或不匹配 missing 字段时匹配重定向,可以使用。source 和所有 has 项必须匹配,并且所有 missing 项必须不匹配,才能应用重定向。

hasmissing 项可以具有以下字段:

  • typeString - 必须是 headercookiehostquery 之一。
  • keyString - 所选类型中要匹配的键。
  • valueStringundefined - 要检查的值,如果为 undefined,任何值都将匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果值 first-(?<paramName>.*) 用于 first-second,则 second 将可在目标中使用 :paramName
next.config.js
module.exports = {
  async redirects() {
    return [
      // 如果存在 header `x-redirect-me`,
      // 将应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'header',
            key: 'x-redirect-me',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果存在 header `x-dont-redirect`,
      // 将不会应用此重定向
      {
        source: '/:path((?!another-page$).*)',
        missing: [
          {
            type: 'header',
            key: 'x-do-not-redirect',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // 如果 source、query 和 cookie 匹配,
      // 将应用此重定向
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // page 值将不会在目标中可用,
            // 因为提供了 value 并且不使用
            // 命名捕获组,例如 (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        permanent: false,
        destination: '/another/:path*',
      },
      // 如果存在 header `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,
      },
      {
        // 不添加 /docs,因为设置了 basePath: false
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
        permanent: false,
      },
    ]
  },
}

使用 i18n 支持的重定向

在 App Router 中实现国际化重定向时,你可以在 next.config.js 重定向中包含语言环境,但只能作为硬编码路径。

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

next.config.js
module.exports = {
  async 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,
      },
    ]
  },
}

在某些罕见情况下,你可能需要为旧版 HTTP 客户端分配自定义状态码以正确重定向。在这些情况下,你可以使用 statusCode 属性而不是 permanent 属性,但不能同时使用两者。为确保 IE11 兼容性,会自动为 308 状态码添加 Refresh header。

其他重定向

版本历史

版本变更
v13.3.0引入 missing
v10.2.0引入 has
v9.5.0引入 redirects