vr技术在网站建设的应用,常见的网站开发语言,黑龙江公共资源交易网官网,wordpress 类似的中间件允许您在请求完成之前运行代码。然后#xff0c;根据传入的请求#xff0c;您可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。 中间件在缓存内容和路由匹配之前运行。
使用规则
使用项目根目录中的文件 middleware.ts#xff08;或 .js#xff09…中间件允许您在请求完成之前运行代码。然后根据传入的请求您可以通过重写、重定向、修改请求或响应标头或直接响应来修改响应。 中间件在缓存内容和路由匹配之前运行。
使用规则
使用项目根目录中的文件 middleware.ts或 .js来定义中间件。例如与页面或应用程序处于同一级别或者在 src 内部如果适用。 // middleware.ts
import { NextResponse } from next/server
import type { NextRequest } from next/server// This function can be marked async if using await inside
export function middleware(request: NextRequest) {return NextResponse.redirect(new URL(/home, request.url))
}// See Matching Paths below to learn more
export const config {matcher: /about/:path*,
}
匹配路径
将为项目中的每个路由调用中间件。以下是执行顺序
headers from next.config.js来自 next.config.js的重定向中间件重写、重定向等来自 next.config.js 的 beforeFiles重写文件系统路由public/、_next/static/、pages/、app/等来自 next.config.js 的 afterFiles重写动态路由 (/blog/[slug])从 next.config.js 回退重写 Matcher (匹配器)
matcher 允许您过滤中间件以在特定路径上运行。
export const config {matcher: /about/:path*,
}
可以使用数组语法匹配单个路径或多个路径
export const config {matcher: [/about/:path*, /dashboard/:path*],
}
匹配器配置允许完整的正则表达式因此支持负向查找或字符匹配等匹配。可以在此处查看用于匹配除特定路径之外的所有路径的负前瞻示例
export const config {matcher: [/** Match all request paths except for the ones starting with:* - api (API routes)* - _next/static (static files)* - _next/image (image optimization files)* - favicon.ico (favicon file)*//((?!api|_next/static|_next/image|favicon.ico).*),],
}
注意
匹配器值需要是常量以便可以在构建时对其进行静态分析。诸如变量之类的动态值将被忽略。
Configured
必须以 / 开头可以包含命名参数 /about/:path 匹配 /about/a 和 /about/b 但不匹配 /about/a/c可以对命名参数进行修饰符以 :) 开头 /about/:path* 匹配 /about/a/b/c 因为 * 为零或更多。 为零或一且一或多个可以使用括号括起来的正则表达式/about/(.*) 与/about/:path* 相同