You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
3.7 KiB
3.7 KiB
Next.js 图片域名配置说明
问题描述
当使用 Next.js 的 Image
组件加载外部图片时,如果图片域名没有在 next.config.ts
中配置,会出现以下错误:
hostname "oss.wsdns.cn" is not configured under images in your `next.config`
解决方案
在 next.config.ts
文件中配置 images.remotePatterns
来允许特定域名的图片加载。
配置示例
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
// OSS 图片域名
{
protocol: 'https',
hostname: 'oss.wsdns.cn',
port: '',
pathname: '/**',
},
{
protocol: 'http',
hostname: 'oss.wsdns.cn',
port: '',
pathname: '/**',
},
// API 服务器图片
{
protocol: 'https',
hostname: 'cms-api.websoft.top',
port: '',
pathname: '/**',
},
// 其他常见 CDN 域名...
],
},
};
export default nextConfig;
配置参数说明
remotePatterns 配置项
- protocol: 协议类型 (
'http'
或'https'
) - hostname: 域名 (支持通配符,如
*.example.com
) - port: 端口号 (通常为空字符串)
- pathname: 路径模式 (通常使用
'/**'
匹配所有路径)
通配符支持
{
protocol: 'https',
hostname: '*.aliyuncs.com', // 匹配所有阿里云 OSS 子域名
pathname: '/**',
}
已配置的域名
当前项目已配置以下图片域名:
主要业务域名
oss.wsdns.cn
- OSS 存储域名cms-api.websoft.top
- API 服务器图片
常见 CDN 域名
*.aliyuncs.com
- 阿里云 OSS*.qiniudn.com
- 七牛云 CDN*.qiniu.com
- 七牛云新域名
开发环境
localhost
- 本地开发
使用示例
配置完成后,可以在组件中正常使用外部图片:
import Image from 'next/image';
function ArticleImage({ article }) {
return (
<Image
src={article.image || '/placeholder.jpg'}
alt={article.title || '文章图片'}
width={400}
height={200}
className="article-image"
/>
);
}
安全注意事项
- 最小权限原则: 只配置必要的域名,避免使用过于宽泛的通配符
- HTTPS 优先: 优先使用 HTTPS 协议的域名
- 路径限制: 如果可能,限制特定的路径模式而不是使用
/**
推荐的安全配置
{
protocol: 'https',
hostname: 'oss.wsdns.cn',
pathname: '/images/**', // 只允许 /images/ 路径下的图片
}
故障排除
1. 配置不生效
解决方案: 修改 next.config.ts
后需要重启开发服务器:
# 停止当前服务器 (Ctrl+C)
npm run dev
2. 通配符不工作
原因: 确保通配符语法正确,只能在域名的开头使用 *
// ✅ 正确
hostname: '*.example.com'
// ❌ 错误
hostname: 'cdn.*.example.com'
3. 图片仍然无法加载
检查步骤:
- 确认域名拼写正确
- 检查协议是否匹配 (http vs https)
- 验证图片 URL 是否可访问
- 查看浏览器控制台错误信息
性能优化建议
- 图片格式: 使用现代图片格式 (WebP, AVIF)
- 尺寸优化: 配置合适的
width
和height
- 懒加载: Next.js Image 组件默认启用懒加载
- 优先级: 对重要图片使用
priority
属性
<Image
src="/hero-image.jpg"
alt="Hero"
width={1200}
height={600}
priority // 优先加载
/>