跳到内容

rewrites

重写允许您将传入的请求路径映射到不同的目标路径。

重写充当 URL 代理并隐藏目标路径,使之看起来用户没有改变他们在网站上的位置。相比之下,重定向将重新路由到新页面并显示 URL 更改。

要使用重写,您可以在 next.config.js 中使用 rewrites

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

重写应用于客户端路由。在上面的示例中,导航到 <Link href="/about"> 将从 / 提供内容,同时保持 URL 为 /about

rewrites 是一个异步函数,期望返回一个数组或一个数组对象(见下文),其中包含具有 sourcedestination 属性的对象

  • source: String - 是传入的请求路径模式。
  • destination: String 是您要路由到的路径。
  • basePath: falseundefined - 如果为 false,则在匹配时不包含 basePath,仅可用于外部重写。
  • locale: falseundefined - 匹配时是否不包含 locale。
  • has 是一个具有 typekeyvalue 属性的 has 对象数组。
  • missing 是一个具有 typekeyvalue 属性的 missing 对象数组。

rewrites 函数返回一个数组时,重写在检查文件系统(页面和 /public 文件)之后和动态路由之前应用。从 Next.js v10.1 开始,当 rewrites 函数返回一个具有特定形状的数组对象时,此行为可以更改并进行更精细的控制。

next.config.js
module.exports = {
  async rewrites() {
    return {
      beforeFiles: [
        // These rewrites are checked after headers/redirects
        // and before all files including _next/public files which
        // allows overriding page files
        {
          source: '/some-page',
          destination: '/somewhere-else',
          has: [{ type: 'query', key: 'overrideMe' }],
        },
      ],
      afterFiles: [
        // These rewrites are checked after pages/public files
        // are checked but before dynamic routes
        {
          source: '/non-existent',
          destination: '/somewhere-else',
        },
      ],
      fallback: [
        // These rewrites are checked after both pages/public files
        // and dynamic routes are checked
        {
          source: '/:path*',
          destination: `https://my-old-site.com/:path*`,
        },
      ],
    }
  },
}

须知beforeFiles 中的重写在匹配源后不会立即检查文件系统/动态路由,它们会一直检查,直到所有 beforeFiles 都被检查过。

Next.js 路由检查顺序是

  1. headers 被检查/应用
  2. redirects 被检查/应用
  3. beforeFiles 重写被检查/应用
  4. 来自 public 目录的静态文件、_next/static 文件和非动态页面被检查/服务
  5. afterFiles 重写被检查/应用,如果其中一个重写匹配,我们会在每次匹配后检查动态路由/静态文件
  6. fallback 重写被检查/应用,这些重写在渲染 404 页面之前和检查所有动态路由/所有静态资产之后应用。如果您在 getStaticPaths 中使用 fallback: true/'blocking',则在 next.config.js 中定义的 fallback rewrites 将**不会**运行。

重写参数

在重写中使用参数时,如果 destination 中没有使用任何参数,则参数默认会在查询中传递。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-about/:path*',
        destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
      },
    ]
  },
}

如果在目标中使用了参数,则所有参数都不会自动在查询中传递。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/docs/:path*',
        destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
      },
    ]
  },
}

如果目标中已使用参数,您仍然可以通过在 destination 中指定查询来手动在查询中传递参数。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/:first/:second',
        destination: '/:first?second=:second',
        // Since the :first parameter is used in the destination the :second parameter
        // will not automatically be added in the query although we can manually add it
        // as shown above
      },
    ]
  },
}

须知:来自 自动静态优化预渲染 的静态页面,其重写参数将在客户端水合后解析并在查询中提供。

路径匹配

允许路径匹配,例如 /blog/:slug 将匹配 /blog/hello-world(无嵌套路径)

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog/:slug',
        destination: '/news/:slug', // Matched parameters can be used in the destination
      },
    ]
  },
}

通配符路径匹配

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

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog/:slug*',
        destination: '/news/:slug*', // Matched parameters can be used in the destination
      },
    ]
  },
}

正则表达式路径匹配

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

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-blog/:post(\\d{1,})',
        destination: '/blog/:post', // Matched parameters can be used in the destination
      },
    ]
  },
}

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

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

要仅在 header、cookie 或查询值也匹配 has 字段或不匹配 missing 字段时才匹配重写,可以使用 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 rewrites() {
    return [
      // if the header `x-rewrite-me` is present,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the header `x-rewrite-me` is not present,
      // this rewrite will be applied
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the source, query, and cookie are matched,
      // this rewrite 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',
          },
        ],
        destination: '/:path*/home',
      },
      // if the header `x-authorized` is present and
      // contains a matching value, this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        destination: '/home?authorized=:authorized',
      },
      // if the host is `example.com`,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        destination: '/another-page',
      },
    ]
  },
}

重写到外部 URL

示例

重写允许您重写到外部 URL。这对于逐步采用 Next.js 特别有用。以下是将主应用的 /blog 路由重定向到外部站点的示例重写。

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog',
        destination: 'https://example.com/blog',
      },
      {
        source: '/blog/:slug',
        destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination
      },
    ]
  },
}

如果您使用 trailingSlash: true,您还需要在 source 参数中插入一个尾部斜杠。如果目标服务器也期望一个尾部斜杠,它也应该包含在 destination 参数中。

next.config.js
module.exports = {
  trailingSlash: true,
  async rewrites() {
    return [
      {
        source: '/blog/',
        destination: 'https://example.com/blog/',
      },
      {
        source: '/blog/:path*/',
        destination: 'https://example.com/blog/:path*/',
      },
    ]
  },
}

Next.js 的增量采用

您还可以让 Next.js 在检查所有 Next.js 路由后回退到代理到现有网站。

这样,当您将更多页面迁移到 Next.js 时,无需更改重写配置

next.config.js
module.exports = {
  async rewrites() {
    return {
      fallback: [
        {
          source: '/:path*',
          destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
        },
      ],
    }
  },
}

支持 basePath 的重写

当在重写中利用 basePath 支持时,除非您在重写中添加 basePath: false,否则每个 sourcedestination 都会自动以 basePath 作为前缀

next.config.js
module.exports = {
  basePath: '/docs',
 
  async rewrites() {
    return [
      {
        source: '/with-basePath', // automatically becomes /docs/with-basePath
        destination: '/another', // automatically becomes /docs/another
      },
      {
        // does not add /docs to /without-basePath since basePath: false is set
        // Note: this can not be used for internal rewrites e.g. `destination: '/another'`
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
      },
    ]
  },
}

支持 i18n 的重写

当在重写中利用 i18n 支持时,除非您在重写中添加 locale: false,否则每个 sourcedestination 都会自动添加前缀以处理配置的 locales。如果使用 locale: false,您必须为 sourcedestination 添加区域设置前缀才能正确匹配。

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async rewrites() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        destination: '/another', // automatically passes the locale on
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        destination: '/en/another',
        locale: false,
      },
      {
        // it's possible to match all locales even when locale: false is set
        source: '/:locale/api-alias/:path*',
        destination: '/api/:path*',
        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',
      },
    ]
  },
}

版本历史

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