跳到内容

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 和 location /v2/users,则后续请求可能是 GET /v2/users 而不是预期的 POST /v2/users。 Next.js 使用 307 临时重定向和 308 永久重定向状态码来显式保留使用的请求方法。

  • basePath: falseundefined - 如果为 false,则匹配时不会包含 basePath,仅可用于外部重定向。
  • locale: falseundefined - 是否在匹配时不应包含 locale。
  • hashas 对象 的数组,具有 typekeyvalue 属性。
  • missingmissing 对象 的数组,具有 typekeyvalue 属性。

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

当使用 Pages Router 时,重定向不应用于客户端路由 (Link, router.push),除非 中间件 存在并匹配路径。

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

{
  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 或 query 值也与 has 字段匹配或与 missing 字段不匹配时才匹配重定向,可以使用 has 字段或 missing 字段。source 和所有 has 项都必须匹配,并且所有 missing 项都必须不匹配,才能应用重定向。

hasmissing 项可以具有以下字段

  • type: String - 必须是 headercookiehostquery 之一。
  • key: String - 要匹配的所选类型的键。
  • value: Stringundefined - 要检查的值,如果为 undefined,则任何值都将匹配。 可以使用类似字符串的正则表达式来捕获值的特定部分,例如,如果为 first-second 使用值 first-(?<paramName>.*),则 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 的重定向

当使用 i18n 支持 进行重定向时,每个 sourcedestination 都会自动添加前缀以处理配置的 locales,除非你向重定向添加 locale: false。 如果使用 locale: false,则必须为 sourcedestination 添加 locale 前缀才能正确匹配。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async redirects() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        destination: '/another', // automatically passes the locale on
        permanent: false,
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
        permanent: false,
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        destination: '/en/another',
        locale: false,
        permanent: false,
      },
      // it's possible to match all locales even when locale: false is set
      {
        source: '/:locale/page',
        destination: '/en/newpage',
        permanent: false,
        locale: false,
      },
      {
        // this gets converted to /(en|fr|de)/(.*) so will not match the top-level
        // `/` or `/fr` routes like /:path* would
        source: '/(.*)',
        destination: '/another',
        permanent: false,
      },
    ]
  },
}

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

其他重定向

版本历史

版本变更
v13.3.0添加了 missing
v10.2.0添加了 has
v9.5.0添加了 redirects