Next.js 15 图片查看网站部署:Vercel 图片资源访问问题与解决方案
在 Next.js 15 中部署图片查看网站到 Vercel 时,常见图片资源访问问题主要涉及路径解析、缓存控制和环境配置。以下是典型问题及解决方案:
常见问题与解决思路
-
问题:生产环境图片 404 错误
- 原因:Vercel 部署后静态资源路径变更,而代码仍使用开发环境路径
- 解决:使用绝对路径代替相对路径
// 错误写法 ❌ <Image src="/images/photo.jpg" alt="Sample" width={500} height={300} /> // 正确写法 ✅ const basePath = process.env.NEXT_PUBLIC_BASE_PATH || ""; <Image src={`${basePath}/images/photo.jpg`} alt="Sample" width={500} height={300} />
-
问题:图片更新后仍显示旧缓存
- 原因:Vercel 边缘缓存未失效
- 解决:在
next.config.js中配置缓存头// next.config.js module.exports = { async headers() { return [ { source: "/images/:path*", headers: [ { key: "Cache-Control", value: "public, max-age=3600, must-revalidate" } ] } ]; } };
-
问题:外部图床加载失败
- 原因:未配置
images.domains白名单 - 解决:在配置中声明外部域名
// next.config.js module.exports = { images: { domains: ["cdn.example.com", "img.third-party.site"], }, };
- 原因:未配置
完整部署流程
-
项目结构优化
public/ ├── images/ # 所有本地图片资源 │ ├── gallery-1.jpg │ └── gallery-2.png -
环境变量配置
# .env.local NEXT_PUBLIC_BASE_PATH="" # .env.production NEXT_PUBLIC_BASE_PATH="https://your-app.vercel.app" -
Vercel 项目设置
- 在控制台添加环境变量:
NEXT_PUBLIC_BASE_PATH = https://your-app.vercel.app - 开启 Automatically expose System Environment Variables
- 在控制台添加环境变量:
验证方案
- 本地测试
npm run build && npm run start - 生产环境检查
- 使用浏览器开发者工具查看图片请求:
- 状态码应为 200
- URL 需匹配实际部署域名
- 响应头包含
Cache-Control配置
- 使用浏览器开发者工具查看图片请求:
补充建议
- 使用
next/font和next/image自动优化资源 - 对于动态图片路径,通过 API 路由代理:
// pages/api/image-proxy.js export default async function handler(req, res) { const { url } = req.query; const response = await fetch(url); res.setHeader("Content-Type", response.headers.get("content-type")); response.body.pipe(res); }
通过上述方案,可解决 90% 的 Vercel 图片资源访问问题。若仍遇异常,检查 Vercel 构建日志中的静态资源处理阶段输出。
2014

被折叠的 条评论
为什么被折叠?



