You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js Image组件加载图片返回403错误 请求协助排查

Next.js Image组件加载图片403错误排查与解决

核心原因

目标服务器amandascookin.com会校验请求的User-Agent,Next.js Image组件默认的请求标识被服务器判定为非合法请求,因此返回403。而代码沙箱环境使用的请求头符合服务器要求,所以能正常加载图片。

具体解决步骤

1. 配置自定义请求头并细化域名规则

修改next.config.js,为图片请求添加浏览器标准的User-Agent,同时把通配符域名改为具体域名(通配符**可能导致配置解析失效):

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "amandascookin.com",
      },
    ],
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
    },
  },
};

2. 验证请求头差异

用curl命令验证不同请求头的返回结果,确认是否是User-Agent导致的问题:

# 模拟Next.js默认请求头
curl -I "https://amandascookin.com/wp-content/uploads/2012/02/Crispy-Potatoes-680.jpg" -A "nextjs-image"
# 模拟浏览器请求头
curl -I "https://amandascookin.com/wp-content/uploads/2012/02/Crispy-Potatoes-680.jpg" -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"

如果第一个命令返回403,第二个返回200,就坐实了User-Agent的问题。

3. 临时绕过图片优化(不推荐用于生产)

如果以上方法无法快速生效,可以临时禁用Next.js的图片优化功能,直接加载原图:

import Image from 'next/image';

export default function YourComponent() {
  return (
    <Image
      src="https://amandascookin.com/wp-content/uploads/2012/02/Crispy-Potatoes-680.jpg"
      alt="Crispy Potatoes"
      width={680}
      height={453}
      unoptimized
    />
  );
}

这个方法会绕过Next.js的图片处理服务,直接从原服务器加载图片,适合临时测试,但会损失图片优化带来的性能收益。

内容的提问来源于stack exchange,提问作者JIMMY JACOB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:37:16