# 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` 来允许特定域名的图片加载。
### 配置示例
```typescript
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**: 路径模式 (通常使用 `'/**'` 匹配所有路径)
### 通配符支持
```typescript
{
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` - 本地开发
## 使用示例
配置完成后,可以在组件中正常使用外部图片:
```tsx
import Image from 'next/image';
function ArticleImage({ article }) {
return (
);
}
```
## 安全注意事项
1. **最小权限原则**: 只配置必要的域名,避免使用过于宽泛的通配符
2. **HTTPS 优先**: 优先使用 HTTPS 协议的域名
3. **路径限制**: 如果可能,限制特定的路径模式而不是使用 `/**`
### 推荐的安全配置
```typescript
{
protocol: 'https',
hostname: 'oss.wsdns.cn',
pathname: '/images/**', // 只允许 /images/ 路径下的图片
}
```
## 故障排除
### 1. 配置不生效
**解决方案**: 修改 `next.config.ts` 后需要重启开发服务器:
```bash
# 停止当前服务器 (Ctrl+C)
npm run dev
```
### 2. 通配符不工作
**原因**: 确保通配符语法正确,只能在域名的开头使用 `*`
```typescript
// ✅ 正确
hostname: '*.example.com'
// ❌ 错误
hostname: 'cdn.*.example.com'
```
### 3. 图片仍然无法加载
**检查步骤**:
1. 确认域名拼写正确
2. 检查协议是否匹配 (http vs https)
3. 验证图片 URL 是否可访问
4. 查看浏览器控制台错误信息
## 性能优化建议
1. **图片格式**: 使用现代图片格式 (WebP, AVIF)
2. **尺寸优化**: 配置合适的 `width` 和 `height`
3. **懒加载**: Next.js Image 组件默认启用懒加载
4. **优先级**: 对重要图片使用 `priority` 属性
```tsx
```
## 相关文档
- [Next.js Image Optimization](https://nextjs.org/docs/basic-features/image-optimization)
- [Next.js Configuration](https://nextjs.org/docs/api-reference/next.config.js/images)