错误:中间件重定向到了包含查询字符串的 URL。重定向必须仅指向路径名。
Error: Middleware redirected to a URL with a query string. Redirects must be to pathnames only.
ID: nextjs/middleware-redirect-to-internal-with-query
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.x | active | — | — | — |
| Next.js 14.x | active | — | — | — |
| Next.js 15.x | active | — | — | — |
根因分析
在 Next.js 中间件中,`redirect` 方法(来自 NextResponse)期望一个不带查询参数的路径名字符串。传递带有查询字符串的 URL 会导致内部错误。
English
In Next.js middleware, the `redirect` method (from NextResponse) expects a pathname string without query parameters. Passing a URL with a query string causes an internal error.
官方文档
https://nextjs.org/docs/app/building-your-application/routing/middleware#redirecting解决方案
-
Redirect to a pathname without query strings, then handle query parameters client-side using useSearchParams or server-side in the target page.
-
Use NextResponse.redirect with a path and then append query parameters via a server-side rewrite or client-side navigation.
无效尝试
常见但无效的做法:
-
80% 失败
The redirect function does not support query strings; it strips them or throws an error.
-
50% 失败
NextResponse.redirect internally validates the URL; setting headers directly bypasses this but may cause hydration or caching issues.
-
60% 失败
Rewrite changes the URL server-side but does not cause a client-side redirect, which may not achieve the desired navigation.