N Next.js 中文
原文 ↗

rewrites

为你的 Next.js 应用添加重写。

更新于 2026-09-28Next.js 16.4.6

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

重写充当 URL 代理并掩盖目标路径,使用户看起来没有改变其在站点上的位置。相比之下,重定向会重新路由到新页面并显示 URL 的变化。

要使用重写,你可以在 next.config.js 中使用 rewrites 键:

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

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

rewrites 可以定义为同步函数或异步函数。它应返回或解析为一个数组,或一个包含数组的对象(见下文),其中持有带有 source 和 destination 属性的对象:

  • source:String - 是传入的请求路径模式。
  • destination:String 是你要路由到的路径。
  • basePath:false 或 undefined - 如果为 false,匹配时将不包含 basePath,仅可用于外部重写。
  • locale:false 或 undefined - 匹配时是否不包含 locale。
  • has 是一个由 has 对象组成的数组,具有 type、key 和 value 属性。
  • missing 是一个由 missing 对象组成的数组,具有 type、key 和 value 属性。

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

next.config.jsjs
module.exports = {
  rewrites() {
    return {
      beforeFiles: [
        // These rewrites are checked after headers/redirects
        // and before all files including _next/static and 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. 检查/应用 重定向
  3. proxy
  4. beforeFiles 重写:对于每个条目,如果 source、has 和 missing 与请求匹配,则会重写到 destination。
  5. public 目录中的静态文件、_next/static 文件以及非动态页面会被检查/提供
  6. afterFiles 重写会按顺序尝试。如果 source、has 和 missing 与请求匹配,则会重写到 destination;第一个解析为静态文件、页面或动态路由的重写将被提供。
  7. 动态路由(例如 app/blog/[slug]/page.tsx)会与当前路径进行匹配
  8. fallback 重写会被检查/应用,这些重写会在渲染 404 页面之前、并在检查完动态路由/所有静态资源之后应用。如果你在 getStaticPaths 中使用 fallback: true/'blocking',这些动态路由会优先于你在 next.config.js 中定义的 fallback rewrites。

重写参数

在重写中使用参数时,如果 destination 中未使用任何参数,则这些参数默认会通过查询传递。

next.config.jsjs
module.exports = {
  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.jsjs
module.exports = {
  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.jsjs
module.exports = {
  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/first-post(不支持嵌套路径):

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

模式 /blog/:slug 匹配 /blog/first-post 和 /blog/post-1,但不匹配 /blog/a/b(不支持嵌套路径)。模式锚定于开头:/blog/:slug 不会匹配 /archive/blog/first-post。

你可以在参数上使用修饰符:*(零个或多个)、+(一个或多个)、?(零个或一个)。例如,/blog/:slug* 匹配 /blog、/blog/a 和 /blog/a/b/c。

更多详情请参阅 path-to-regexp 文档。

通配符路径匹配

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

next.config.jsjs
module.exports = {
  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.jsjs
module.exports = {
  rewrites() {
    return [
      {
        source: '/old-blog/:post(\\d{1,})',
        destination: '/blog/:post', // Matched parameters can be used in the destination
      },
    ]
  },
}

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

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

请求头、Cookie 和查询匹配

若要仅在请求头、Cookie 或查询值也匹配时才触发重写,可以使用 has 字段(值匹配)或 missing 字段(值不匹配)。只有 source 以及所有 has 项都匹配,且所有 missing 项都不匹配时,才会应用该重写。

has 和 missing 项可以包含以下字段:

  • type:String - 必须是 header、cookie、host 或 query 之一。
  • key:String - 要匹配的键,来自所选类型。
  • value:String 或 undefined - 要检查的值,如果为 undefined,则任何值都会匹配。可以使用类似正则的字符串来捕获值的特定部分,例如,如果为 first-second 使用值 first-(?<paramName>.*),那么可以在目标中通过 :paramName 使用 second。
next.config.jsjs
module.exports = {
  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.jsjs
module.exports = {
  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.jsjs
module.exports = {
  trailingSlash: true,
  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.jsjs
module.exports = {
  rewrites() {
    return {
      fallback: [
        {
          source: '/:path*',
          destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
        },
      ],
    }
  },
}

支持 basePath 的重写

在重写中使用 basePath 支持 时,每个 source 和 destination 都会自动添加 basePath 前缀,除非你在重写中添加 basePath: false:

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

  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 cannot be used for internal rewrites e.g. `destination: '/another'`
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
      },
    ]
  },
}

版本历史

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