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

Next.js图片优化器为何在远程图片URL前添加域名路径?

问题描述

我在应用中使用next-image-export-optimizer库的ExportedImage组件,代码如下:

import ExportedImage from 'next-image-export-optimizer'

<ExportedImage src={media?.original_url} fill sizes="100vw" alt={title} placeholder="em>

其中media.original_url的值为'https://s3.eu-west-2.amazonaws.com/getnarval-test/domains/9909f63c-9b13-48a9-9d2d-ea01a7b37c95/1/person.jpg'。应用中图片可正常显示,但控制台出现错误。

我的next.config.js配置如下:

/** @type {import('next').NextConfig} */

const withBundleAnalyzer = require('@next/bundle-analyzer')({
    enabled: true,
    openAnalyzer: true
})

const nextConfig = {
    reactStrictMode: true,
    compiler: {
        styledComponents: true
    },
    images: {
        loader: 'custom',
        imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
        deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
        remotePatterns: [
            {
                protocol: 'https',
                hostname: '*.amazonaws.com',
                pathname: '**'
            },
            {
                protocol: 'https',
                hostname: 'eu.ui-avatars.com',
                pathname: '**'
            }
        ]
    },
    env: {
        nextImageExportOptimizer_imageFolderPath: 'public/img',
        nextImageExportOptimizer_exportFolderPath: 'out',
        nextImageExportOptimizer_quality: 75,
        nextImageExportOptimizer_storePicturesInWEBP: true,

        // If you do not want to use blurry placeholder images, then you can set
        // nextImageExportOptimizer_generateAndUseBlurImages to false and pass
        // `placeholder="empty"` to all <ExportedImage> components.
        //
        // If nextImageExportOptimizer_generateAndUseBlurImages is false and you
        // forget to set `placeholder="empty"`, you'll see 404 errors for the missing
        // placeholder images in the console.
        nextImageExportOptimizer_generateAndUseBlurImages: true
    },
    trailingSlash: true
}

module.exports = nextConfig

我尝试使用不带http/https的URL(如//s3.eu-west-2.amazonaws.com/getnarval-test/domains/9909f63c-9b13-48a9-9d2d-ea01a7b37c95/1/person.jpg),此时不会添加域名,但Next.js会将其视为http协议,我需要找到将//映射为https的方法。


解决方案

1. 先修复组件语法错误

你的ExportedImage组件代码中placeholder="em>存在语法错误,缺少闭合引号且值不合法,需先修正为合法值(如"blur"、"empty"),这可能是控制台报错的原因之一:

<ExportedImage 
  src={media?.original_url} 
  fill 
  sizes="100vw" 
  alt={title} 
  placeholder="blur"
/>

2. 手动统一URL协议

在传入src时,强制将所有URL转换为HTTPS协议:

const formatImageUrl = (url) => {
  if (!url) return '';
  // 替换http开头或//开头的URL为https
  return url.replace(/^http:\/\//, 'https://').replace(/^\/\//, 'https://');
};

// 使用时
<ExportedImage 
  src={formatImageUrl(media?.original_url)} 
  fill 
  sizes="100vw" 
  alt={title} 
  placeholder="blur"
/>

3. 通过自定义Loader强制HTTPS

因为你配置了loader: 'custom',可以自定义加载逻辑统一处理协议:

  • 修改next.config.js的images配置:
images: {
  loader: 'custom',
  loaderFile: './image-loader.js', // 指定自定义loader文件
  // 其他原有配置...
}
  • 在项目根目录创建image-loader.js:
export default function imageLoader({ src }) {
  // 处理//开头的URL,强制转为https
  if (src.startsWith('//')) {
    return `https:${src}`;
  }
  // 其他情况保持原URL
  return src;
}

4. 适配远程图片的env配置

next-image-export-optimizer默认优先处理本地图片,确保env配置正确适配远程资源,同时结合上述URL格式化方法,可避免协议不匹配问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:35:17