跳到内容

redirects

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

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

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

redirects 是一个异步函数,它期望返回一个数组,其中包含带有 sourcedestinationpermanent 属性的对象。

  • source 是传入请求的路径模式。
  • destination 是你想要路由到的路径。
  • permanent truefalse - 如果为 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 - 匹配时是否不包含 locale。
  • has 是一个具有 typekeyvalue 属性的 has 对象数组。
  • missing 是一个具有 typekeyvalue 属性的 missing 对象数组。

重定向在文件系统(包括页面和 /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', // Matched parameters can be used in the destination
        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*', // Matched parameters can be used in the destination
        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', // Matched parameters can be used in the destination
        permanent: false,
      },
    ]
  },
}

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

next.config.js
module.exports = {
  async redirects() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        destination: '/en-us/:slug',
        permanent: false,
      },
    ]
  },
}

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

hasmissing 项可以具有以下字段

  • type: String - 必须是 headercookiehostquery
  • key: String - 要匹配的所选类型的键。
  • value: Stringundefined - 要检查的值,如果未定义,则任何值都将匹配。可以使用类似正则表达式的字符串来捕获值的特定部分,例如,如果 first-(?<paramName>.*) 用于 first-second,那么 second 将在目标中与 :paramName 一起使用。
next.config.js
module.exports = {
  async redirects() {
    return [
      // if the header `x-redirect-me` is present,
      // this redirect will be applied
      {
        source: '/:path((?!another-page$).*)',
        has: [
          {
            type: 'header',
            key: 'x-redirect-me',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // if the header `x-dont-redirect` is present,
      // this redirect will NOT be applied
      {
        source: '/:path((?!another-page$).*)',
        missing: [
          {
            type: 'header',
            key: 'x-do-not-redirect',
          },
        ],
        permanent: false,
        destination: '/another-page',
      },
      // if the source, query, and cookie are matched,
      // this redirect will be applied
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // the page value will not be available in the
            // destination since value is provided and doesn't
            // use a named capture group e.g. (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        permanent: false,
        destination: '/another/:path*',
      },
      // if the header `x-authorized` is present and
      // contains a matching value, this redirect will be applied
      {
        source: '/',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        permanent: false,
        destination: '/home?authorized=:authorized',
      },
      // if the host is `example.com`,
      // this redirect will be applied
      {
        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', // automatically becomes /docs/with-basePath
        destination: '/another', // automatically becomes /docs/another
        permanent: false,
      },
      {
        // does not add /docs since basePath: false is set
        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 [
      {
        // Manually handle locale prefixes for App Router
        source: '/en/old-path',
        destination: '/en/new-path',
        permanent: false,
      },
      {
        // Redirect for all locales using a parameter
        source: '/:locale/old-path',
        destination: '/:locale/new-path',
        permanent: false,
      },
      {
        // Redirect from one locale to another
        source: '/de/old-path',
        destination: '/en/new-path',
        permanent: false,
      },
      {
        // Catch-all redirect for multiple locales
        source: '/:locale(en|fr|de)/:path*',
        destination: '/:locale/new-section/:path*',
        permanent: false,
      },
    ]
  },
}

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

其他重定向

版本历史

版本更改
v13.3.0missing 已添加。
v10.2.0has 已添加。
v9.5.0redirects 已添加。