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

- **ID:** `nextjs/middleware-rewrite-absolute-url`
- **Domain:** nextjs
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 14.2.0 | active | — | — |
| 15.0.0 | active | — | — |
| 14.2.15 | active | — | — |

## Workarounds

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.** (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.
   ```
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).** (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).
   ```

## Dead Ends

- **Adding trailing slash or encoding the URL** — The issue is the domain mismatch, not URL formatting. Trailing slashes or encoding don't change the absolute external nature. (80% fail)
- **Using NextResponse.redirect() instead of rewrite()** — Redirect also expects a relative path or internal URL in this context; it's not a rewrite-specific restriction. (70% fail)
- **Setting headers to allow external redirects** — Middleware rewrites are fundamentally disallowed for external URLs regardless of headers. The restriction is baked into Next.js's routing logic. (90% fail)
