nextjs config_error ai_generated true

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

ID: nextjs/middleware-rewrite-absolute-url

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14.2.0 active
15.0.0 active
14.2.15 active

Root Cause

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

中文

中间件使用 NextResponse.rewrite() 时传入了绝对外部 URL,而非相对路径或内部路由。Next.js 中间件重写仅限于同源路径。

Official Documentation

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

Workarounds

  1. 95% success 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.
    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. 85% success 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).
    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. 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).

Dead Ends

Common approaches that don't work:

  1. Adding trailing slash or encoding the URL 80% fail

    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% fail

    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% fail

    Middleware rewrites are fundamentally disallowed for external URLs regardless of headers. The restriction is baked into Next.js's routing logic.