错误:URL 无效。中间件重写目标必须是相对路径或内部 URL。
Error: URL is not valid. Middleware rewrite target must be a relative path or internal URL.
ID: nextjs/middleware-rewrite-absolute-url
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 14.2.0 | active | — | — | — |
| 15.0.0 | active | — | — | — |
| 14.2.15 | active | — | — | — |
根因分析
中间件使用 NextResponse.rewrite() 时传入了绝对外部 URL,而非相对路径或内部路由。Next.js 中间件重写仅限于同源路径。
English
Middleware uses NextResponse.rewrite() with an absolute external URL instead of a relative path or internal route. Next.js middleware rewrites are restricted to same-origin paths.
官方文档
https://nextjs.org/docs/app/api-reference/functions/next-response#rewrite解决方案
-
Change the rewrite target to a relative path. If you need to proxy an external URL, create an API route that fetches the external resource and returns it.
-
Use NextResponse.next() and modify the response headers to forward the request to an external service via a reverse proxy setup (e.g., Nginx or Vercel rewrites in vercel.json).
无效尝试
常见但无效的做法:
-
Adding trailing slash or encoding the URL
80% 失败
The issue is the domain mismatch, not URL formatting. Trailing slashes or encoding don't change the absolute external nature.
-
Using NextResponse.redirect() instead of rewrite()
70% 失败
Redirect also expects a relative path or internal URL in this context; it's not a rewrite-specific restriction.
-
Setting headers to allow external redirects
90% 失败
Middleware rewrites are fundamentally disallowed for external URLs regardless of headers. The restriction is baked into Next.js's routing logic.