使用nextjs构建的前端应用
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

Next.js 图片域名配置修复总结

问题描述

在使用 Next.js 的 Image 组件加载外部图片时,出现以下错误:

hostname "oss.wsdns.cn" is not configured under images in your `next.config`

解决方案

1. 修改 next.config.ts 文件

在 Next.js 配置文件中添加了 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: '/**',
      },
      {
        protocol: 'http',
        hostname: 'cms-api.websoft.top',
        port: '',
        pathname: '/**',
      },
      // 常见的图片 CDN 域名
      {
        protocol: 'https',
        hostname: '*.aliyuncs.com',
        port: '',
        pathname: '/**',
      },
      {
        protocol: 'https',
        hostname: '*.qiniudn.com',
        port: '',
        pathname: '/**',
      },
      {
        protocol: 'https',
        hostname: '*.qiniu.com',
        port: '',
        pathname: '/**',
      },
      // 本地开发
      {
        protocol: 'http',
        hostname: 'localhost',
        port: '',
        pathname: '/**',
      },
      {
        protocol: 'https',
        hostname: 'localhost',
        port: '',
        pathname: '/**',
      },
    ],
  },
};

export default nextConfig;

2. 配置的域名列表

已配置的图片域名包括:

主要业务域名

  • oss.wsdns.cn - OSS 存储域名(HTTP/HTTPS)
  • cms-api.websoft.top - API 服务器图片(HTTP/HTTPS)

常见 CDN 域名

  • *.aliyuncs.com - 阿里云 OSS
  • *.qiniudn.com - 七牛云 CDN
  • *.qiniu.com - 七牛云新域名

开发环境

  • localhost - 本地开发(HTTP/HTTPS)

3. 重启服务器

修改 next.config.ts 后需要重启开发服务器:

# 停止当前服务器 (Ctrl+C)
npm run dev

修复效果

已解决的问题

  1. 外部图片加载:现在可以正常加载来自 oss.wsdns.cn 的图片
  2. API 图片支持:支持从 cms-api.websoft.top 加载图片
  3. CDN 兼容性:支持常见的 CDN 域名
  4. 开发环境:支持本地开发时的图片加载

⚠️ 注意事项

  1. 404 错误正常:日志中的 /hero-image.jpg/about-image.jpg 等 404 错误是正常的,因为这些本地图片文件不存在
  2. Tailwind 警告px-6 等 Tailwind 类的警告不影响图片功能
  3. 配置生效:服务器已自动重启并应用了新配置

使用示例

现在可以在组件中正常使用外部图片:

import Image from 'next/image';

function ArticleImage({ article }) {
  return (
    <Image
      src={article.image || '/placeholder.jpg'} // 支持 oss.wsdns.cn 域名
      alt={article.title || '文章图片'}
      width={400}
      height={200}
      className="article-image"
    />
  );
}

安全考虑

  1. 最小权限:只配置了必要的域名
  2. 协议支持:同时支持 HTTP 和 HTTPS
  3. 路径限制:使用 /** 允许所有路径(可根据需要进一步限制)

相关文档

状态

已完成 - 图片域名配置问题已解决,外部图片可以正常加载