如何允许所有域名在Image nextjs配置中使用?

33

我有许多图片URL,它们会随着时间而变化(这些图片是通过URL地址从网络上获取的,而不是存储在本地或私人存储中)。为了呈现<Image />标签,需要将域名传递给Next.js配置文件。

不可能随着时间的推移传递数百个URL。

如何允许所有域名?

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: [
      "img.etimg.com",
      "assets.vogue.com",
      "m.media-amazon.com",
      "upload.wikimedia.org",
    ],
  },
};

module.exports = nextConfig;

我尝试过这个但没成功,"*.com"



另一种选择是使用 <img /> 标签代替 Next JS 的 <Image /> 标签。 - Mohammad Tbeishat
我目前正在使用普通的img标签,但我想使用next的Image标签来获得更好的优化。 - Sai Krishnadas
你可以尝试在Loader中使用正则表达式。 https://nextjs.org/docs/api-reference/next/image#loader - Mohammad Tbeishat
3个回答

70
根据Next.js文档,这对我很有效。

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "**",
      },
    ],
  },
};

Next.js 配置选项


2
remotePatterns 存在于 v12.3.0 版本中。它作为实验性功能首次出现在 v12.2.0 中。 - Advena
为什么这个https://www.si.com会失败?它可以处理其他所有的URL,但是这个还是出错。 - Florian Walther
请告诉我,我已经更新了 Next.js 12.3.4,并且使用了 remotePatterns。但是在构建时,遇到了图像问题(“url”参数不被允许)。你有遇到过这样的情况吗?我在以下主题中更详细地描述了问题:https://github.com/vercel/next.js/discussions/50028,https://dev59.com/SPUgpYgB1922wOYJZ7aI。 - XAZG Неизвестный

16

根据文档,域名必须明确指定。

为了保护应用免受恶意用户的攻击,您必须定义一个图像提供商域名列表,以便从Next.js图像优化API中提供服务。

您还可以看到源代码允许评估URL,但不接受通配符。

https://github.com/vercel/next.js/blob/canary/packages/next/client/image.tsx#L864

解决方法

您应该考虑使用像cloudinary或imgix这样的代理,并在next.config中允许这些域名,并使用它们的fetch功能加载外部图像。

例如:

允许cloudinary作为域名

module.exports = {
  images: {
    domains: ['res.cloudinary.com'],
  },
};

然后在你的代码中

<Image
src="https://res.cloudinary.com/demo/image/fetch/https://a.travel-assets.com/mad-service/header/takeover/expedia_marquee_refresh.jpg"
width={500}
height={500}
/>

重要

以下 StackBlitz 利用他们的演示账户从 Expedia.com 获取外部图片,您应该为生产获取自己的账户。

https://stackblitz.com/edit/nextjs-pxrg99?file=pages%2Findex.js


1
请参阅 https://nextjs.org/docs/api-reference/next/image#loader-configuration,现在有一个专门的选项用于加载器。 - Moritz Schmitz v. Hülst
据我理解,该问题要求允许所有域名 - 即使使用自定义的“loader”,您也必须明确指定URL字符串。 - Ramakay
是的,你建议将 res.cloudinary.com 域名加入白名单,然后使用 fetch API。但实际上,你可以直接使用 Cloudinary loader,不需要在实际 URL 前面添加 Cloudinary URL。 - Moritz Schmitz v. Hülst

1

在 NextJs 14 中,images.domains 已被弃用。

要参考 Next.js 的新文档,您需要在 next.config.js 文件中使用以下代码。

const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "www.your-website.com", // if your website has no www, drop it
      },
      {
        protocol: "http",
        hostname: "localhost",
      },
    ],
  },
};
module.exports = nextConfig;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接