nextjs config_error ai_generated true

错误:URL 无效。中间件重写目标必须是相对路径或内部 URL。

Error: URL is not valid. Middleware rewrite target must be a relative path or internal URL.

ID: nextjs/middleware-rewrite-absolute-url

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://nextjs.org/docs/app/api-reference/functions/next-response#rewrite

解决方案

  1. 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.
  2. 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).

无效尝试

常见但无效的做法:

  1. 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.

  2. 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.

  3. 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.