img-src Directive for Image Sources

Configure the img-src CSP directive to control image loading sources. Cover data URIs, blob URLs, CDN allowlists, and third-party image providers like Gravatar and Cloudinary.

Directives

Detailed Explanation

The img-src Directive

The img-src directive specifies valid sources for images loaded via <img> tags, CSS background-image, <picture> elements, and the image() CSS function. Properly configuring img-src prevents image-based tracking pixels and data exfiltration.

Basic Syntax

Content-Security-Policy: img-src 'self' https://images.example.com

Common Source Patterns

Allow data URIs (inline images, base64-encoded):

img-src 'self' data:

Data URIs are commonly used for:

  • Small icons and placeholders
  • Dynamically generated images (canvas toDataURL())
  • Inline SVG as data URIs
  • Image preview thumbnails

Allow blob URLs (generated from JavaScript):

img-src 'self' blob:

Blob URLs are created by URL.createObjectURL() and are used for:

  • File upload previews
  • Images processed by Web Workers
  • Screenshots captured with html2canvas

Allow a CDN with wildcards:

img-src 'self' https://*.cloudinary.com https://*.imgix.net

Real-World Policy Examples

Blog with user avatars and CDN images:

img-src 'self' https://res.cloudinary.com https://www.gravatar.com data:

E-commerce with product images and tracking pixels:

img-src 'self' https://images.shopify.com https://www.google-analytics.com https://www.facebook.com

Note: many analytics and advertising platforms use image pixels (1x1 transparent GIFs) for tracking. Blocking these via img-src also blocks their tracking capabilities.

Single-page app with dynamic image generation:

img-src 'self' blob: data:

Security Considerations

  • Avoid img-src * — this allows images from any source, enabling tracking pixels
  • Be cautious with data: — while generally safe for images, data URIs bypass origin restrictions
  • Wildcards on subdomains (*.example.com) are safer than on TLDs
  • SVG images can contain JavaScript — img-src restrictions apply to SVG loaded as images, but inline SVG in HTML is governed by script-src

Interaction with Other Directives

Images in CSS background-image are controlled by img-src, not style-src. Favicon loading is also governed by img-src. If img-src is not set, it falls back to default-src.

Use Case

Configuring img-src is essential for sites that load images from CDNs, user-uploaded content platforms, or third-party services. A news site using Cloudinary for image optimization needs to allowlist Cloudinary domains. A SaaS dashboard generating charts as images needs blob: and data: support. Properly restricting img-src also blocks unwanted tracking pixels from ad networks.

Try It — CSP Header Generator

Open full tool