如何配置Next.js Middleware匹配含编码字符串的路径?
解决Next.js Middleware仅在路径含编码字符串时触发的问题
你当前的matcher配置不符合Next.js的语法规范,导致无法正确匹配含编码字符的路径。以下是具体的解决方案:
正确的Matcher配置
Next.js Middleware的matcher支持glob模式或正则表达式(需用/(...)/包裹),要匹配所有包含%(URL编码的标志性字符)的路径,可使用正则表达式形式的规则:
export const config = { matcher: '/.*%.*$' }
规则说明:
.*匹配任意长度的任意字符%精准匹配URL编码的起始标识$匹配路径结尾- 整体作用:仅拦截路径中包含至少一个
%的请求
优化后的完整Middleware代码
结合你的业务逻辑,优化后的代码如下:
// middleware.ts import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { const originalPath = request.nextUrl.pathname const decodedPath = decodeURIComponent(originalPath) // 仅当解码前后路径不同时执行重定向 if (decodedPath !== originalPath) { const redirectUrl = new URL(decodedPath, request.url) return NextResponse.redirect(redirectUrl) } // 无需处理时放行请求 return NextResponse.next() } export const config = { matcher: '/.*%.*$' }
额外场景处理
- 双重编码适配:若遇到部分网站做了双重编码(如
%2520对应空格),可循环解码直到路径不再变化:
let decodedPath = request.nextUrl.pathname let prevPath: string do { prevPath = decodedPath decodedPath = decodeURIComponent(decodedPath) } while (decodedPath !== prevPath)
- 排除静态资源:若不想处理静态资源(如图片、样式文件),可在matcher中添加排除规则:
export const config = { matcher: [ '/.*%.*$', '!/images/:path*', '!/css/:path*' ] }
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

