rewrites
重写允许你将传入请求路径映射到不同的目标路径。
重写充当 URL 代理并掩盖目标路径,使其看起来用户没有在站点上更改位置。相比之下,重定向 将重新路由到新页面并显示 URL 更改。
要使 用重写,你可以在 next.config.js
中使用 rewrites
键:
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
重写应用于客户端路由,在上面的示例中,<Link href="/about">
将应用重写。
rewrites
是一个异步函数,期望返回一个数组或数组对象(见下文),包含具有 source
和 destination
属性的对象:
source
:String
- 是传入请求路径模式。destination
:String
是你想要路由到的路径。basePath
:false
或undefined
- 如果为 false,匹配时不会包含 basePath,仅可用于外部重写。locale
:false
或undefined
- 匹配时是否不应包含区域设置。has
是具有type
、key
和value
属性的 has 对象 数组。missing
是具有type
、key
和value
属性的 missing 对象 数组。
当 rewrites
函数返回数组时,重写在检查文件系统(页面和 /public
文件)之后、动态路由之前应用。当 rewrites
函数返回具有特定形状的数组对象时,从 Next.js 的 v10.1
开始,可以更改和更精细地控制此行为:
next.config.js
module.exports = {
async rewrites() {
return {
beforeFiles: [
// 这些重写在头部/重定向之后检查
// 在所有文件(包括 _next/public 文件)之前,
// 允许覆盖页面文件
{
source: '/some-page',
destination: '/somewhere-else',
has: [{ type: 'query', key: 'overrideMe' }],
},
],
afterFiles: [
// 这些重写在页面/公共文件检查之后检查
// 但在动态路由之前
{
source: '/non-existent',
destination: '/somewhere-else',
},
],
fallback: [
// 这些重写在页面/公共文件和动态路由都检查之后检查
{
source: '/:path*',
destination: `https://my-old-site.com/:path*`,
},
],
}
},
}
提示:
beforeFiles
中的重写在匹配源后不会立即检查文件系统/动态路由,它们会继续直到所有beforeFiles
都被检查。
Next.js 路由检查的顺序是:
- 检查/应用 头部
- 检查/应用 重定向
- 检查/应用
beforeFiles
重写 - 检查/服务来自 公共目录、
_next/static
文件和非动态页面的静态文件 - 检查/应用
afterFiles
重写,如果匹配其中一个重写,我们在每次匹配后检查动态路由/静态文件 - 检查/应用
fallback
重写,这些在渲染 404 页面之前应用,在动态路由/所有静态资源检查之后应用。如果你在getStaticPaths
中使用 fallback: true/'blocking',你在next.config.js
中定义的 fallbackrewrites
将不会运行。
重写参数
在重写中使用参数时,当 destination
中未使用任何参数时,参数将默认在查询中传递。
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/old-about/:path*',
destination: '/about', // 这里未使用 :path 参数,所以会自动在查询中传递
},
]
},
}
如果在目标中使用了参数,则不会自动在查询中传递任何参数。
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/docs/:path*',
destination: '/:path*', // 这里使用了 :path 参数,所以不会自动在查询中传递
},
]
},
}
如果目标中已经使用了一个参数,你仍然可以通过在 destination
中指定查询来手动在查询中传递参数。
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/:first/:second',
destination: '/:first?second=:second',
// 由于 :first 参数在目标中使用,:second 参数
// 不会自动添加到查询中,尽管我们可以手动添加它
// 如上所示
},
]
},
}
路径匹配
允许路径匹配,例如 /blog/:slug
将匹配 /blog/hello-world
(无嵌套路径):
next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug',
destination: '/news/:slug', // 匹配的参数可以在目标中使用
},
]
},
}