错误:图像优化失败,URL '...' 返回 403 状态。远程服务器阻止了请求。
Error: Image optimization failed for URL '...' with status 403. The remote server blocked the request.
ID: nextjs/invalid-image-optimization-url
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
Next.js 图像组件尝试通过获取远程图像来优化它们,但远程服务器的防火墙或 CORS 策略阻止了来自 Next.js 服务器的请求,通常是由于缺少或不正确的 User-Agent 标头。
English
Next.js Image component tries to optimize remote images by fetching them, but the remote server's firewall or CORS policy blocks requests from the Next.js server, typically due to missing or incorrect User-Agent headers.
官方文档
https://nextjs.org/docs/app/api-reference/components/image#remote-patterns解决方案
-
Configure a custom loader in next.config.js that sets the proper User-Agent header when proxying requests to the remote server.
-
Use a reverse proxy or middleware to fetch the image with a custom User-Agent before passing it to the Image component.
无效尝试
常见但无效的做法:
-
50% 失败
This only configures allowed domains for the Image component, but doesn't change the request headers that the server sends when fetching the image.
-
30% 失败
This bypasses optimization entirely, which defeats the purpose and may degrade performance. It's a workaround but doesn't fix the root cause.