错误:无效的重写目标。重写目标必须是相对路径或同一应用程序内的绝对 URL。
Error: Invalid rewrite destination. Rewrite destination must be a relative path or an absolute URL within the same application.
ID: nextjs/rewrite-invalid-destination
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.0.0 | active | — | — | — |
| Next.js 14.0.0 | active | — | — | — |
| Next.js 14.2.0 | active | — | — | — |
根因分析
next.config.js 中的重写规则有一个指向外部 URL(例如 https://other-site.com)或无效路径的 `destination`,但 Next.js 中的重写只允许重定向到同一应用程序内的内部路由。
English
A rewrite rule in next.config.js has a `destination` that points to an external URL (e.g., https://other-site.com) or an invalid path, but rewrites in Next.js are only allowed to redirect to internal routes within the same application.
官方文档
https://nextjs.org/docs/app/api-reference/next-config-js/rewrites解决方案
-
将目标更改为应用程序内的相对路径。示例:`rewrites: async () => [{ source: '/old-path', destination: '/new-path' }]`。如果需要代理外部 API,请改用 API 路由。 -
如果需要代理外部 API,请创建一个从外部 URL 获取数据并返回响应的 API 路由。示例:在 app/api/proxy/route.ts 中,使用 `fetch('https://other-site.com/api/data')` 并返回结果。 -
使用中间件通过返回包含外部内容的 Response 对象来重写请求到外部 URL。示例:在 middleware.ts 中,`return fetch('https://other-site.com' + request.nextUrl.pathname)`。
无效尝试
常见但无效的做法:
-
100% 失败
The destination is still external; Next.js does not allow rewrites to external URLs regardless of formatting.
-
50% 失败
Redirects to external URLs are allowed, but if the intent was to proxy content (rewrite), this changes the URL in the browser, which may not be desired.
-
95% 失败
The basePath option only affects the application's own URL prefix, not rewrite destinations; the error will persist.