# 错误：中间件重定向到外部 URL。重定向必须是相对路径或内部路由。

- **ID:** `nextjs/middleware-redirect-to-external-url`
- **领域:** nextjs
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

Next.js 中间件限制 NextResponse.redirect() 方法仅接受相对 URL 或同一应用程序内的路径，以防止开放重定向的安全问题。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 13.5.0 | active | — | — |
| 14.0.0 | active | — | — |
| 14.1.0 | active | — | — |
| 15.0.0 | active | — | — |

## 解决方案

1. ```
   Redirect to a relative path within your app and then handle the external redirect on the client side using useEffect or a Server Action. Example: export function middleware(request) { return NextResponse.redirect(new URL('/external-redirect', request.url)); } Then in the /external-redirect page, call window.location.href = 'https://example.com'.
   ```
2. ```
   Use NextResponse.next() and set a custom header to signal the client to redirect, then read that header in a layout or page component.
   ```

## 无效尝试

- **Using window.location.href inside middleware to redirect externally** — Middleware runs on the server/edge runtime, not in the browser. window is not defined. (100% 失败率)
- **Setting the Location header manually in the middleware response** — Next.js middleware response headers are immutable for security; manual header manipulation is ignored or causes a different error. (80% 失败率)
