Serve Next-Gen Images on Nginx: Map, Try_Files, Cache

As websites grow increasingly media-rich, serving modern image formats becomes essential to improving loading speed and overall user experience. Next-generation image formats like WebP and AVIF provide superior compression and visual quality compared to legacy formats like JPEG and PNG. Leveraging Nginx to intelligently serve these optimized assets can result in faster page loads and lower bandwidth consumption.

TLDR: Serving next-gen images like WebP through Nginx significantly boosts performance and reduces bandwidth usage. Using map, try_files, and efficient caching techniques can enable graceful fallbacks when next-gen image support is absent. This guide walks through how to configure Nginx to detect browser capabilities and deliver the most optimized image format available. These optimizations are simple to implement and have immediate, measurable benefits.

Why Serve Next-Gen Images?

Modern image formats bring several advantages:

  • WebP offers ~25% smaller file sizes than JPEG with promising quality.
  • AVIF compresses images even further while maintaining advanced features like HDR and better transparency.
  • Reduced image payload means lower network usage and faster page render times.

However, not all browsers support every next-gen format. For instance, Safari only began supporting WebP in version 14, and AVIF adoption is still rising. To serve the optimal file to each user, we must check browser support dynamically—this is where Nginx shines.

Architecture Overview

Here’s the approach we’ll cover:

  1. Inspect the Accept header from the browser to detect support for WebP or AVIF.
  2. Use the map directive to decide which image format to serve.
  3. Implement try_files to gracefully fall back to older formats if next-gen variants are unavailable.
  4. Enable caching to reduce server load and accelerate future requests.

This method is highly customizable, scalable, and does not depend on JavaScript support or client-side logic.

Step 1: Browser Detection via Accept Header

Nginx’s map directive allows you to define variables based on incoming headers. In this case, we examine the Accept header to infer which image formats the client supports.

map $http_accept $webp_support {
    default         0;
    "~*webp"        1;
}

This configuration maps the variable $webp_support to 1 if the client’s Accept header contains “webp”, and 0 otherwise. You can extend this further to check for AVIF or other formats like so:

map $http_accept $preferred_img_extension {
    "~*avif"        ".avif";
    "~*webp"        ".webp";
    default         "";
}

Now you can use $preferred_img_extension to help select which image file to serve based on what’s available and supported.

Step 2: Using try_files for Graceful Fallback

Let’s say your image directory contains multiple versions of the same image:

  • /images/sample.avif
  • /images/sample.webp
  • /images/sample.jpg

You can use try_files in the location block of your site to attempt delivery of more optimized formats first:

location ~* ^/images/(.+)\.(jpg|jpeg|png)$ {
    set $img_uri $uri;
    set $basename $1;

    try_files
        /images/$basename$preferred_img_extension
        $img_uri
        =404;
}

This configuration works as follows:

  1. Attempts to serve .avif or .webp by appending the preferred extension.
  2. If not found, falls back to the original image format (JPEG or PNG).
  3. If no matching file exists, returns a 404 error.

This technique ensures compatibility without needing to duplicate HTML or overcomplicate backend logic. Efficient and straightforward.

Image not found in postmeta

Step 3: Enable Smart Caching

Images are typically ideal candidates for caching. Consider enabling expires and cache-control headers on your images to reduce repeat server hits and improve CDN performance.

location ~* \.(?:jpg|jpeg|gif|png|webp|avif)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
}

The immutable directive tells browsers they can safely reuse the image asset unless its URL changes. For static content like images, this is an enormous bandwidth saver and helps reduce load on origin servers.

Use with Image Conversion Pipelines

Of course, to benefit from this setup, you have to generate next-gen images in the first place. Many modern build pipelines or CMS platforms already do this, such as:

  • ImageMagick with CLI scripts for automated batch conversion.
  • Sharp in Node.js-based image projects.
  • WordPress plugins that auto-generate WebP versions on upload.

Once generated, placing these files alongside their original versions allows your mapped Nginx setup to serve the optimal one per user.

Test and Validate

Before going live, it’s essential to verify the configuration:

  1. Use browser dev tools to inspect which image format is being served.
  2. Employ curl -H "Accept: image/webp" to simulate various clients.
  3. Ensure all fallback paths and MIME types are correctly configured in Nginx.

Testing prevents unexpected behaviors and ensures smooth cross-browser delivery.

Optional: Handle AVIF vs WebP Priority

If you support multiple next-gen formats like AVIF and WebP, AVIF should usually take precedence due to its better compression. You can adapt your map block to make that distinction:

map $http_accept $preferred_img_extension {
    "~*avif"        ".avif";
    "~*webp"        ".webp";
    default         "";
}

This ensures AVIF is attempted first, followed by WebP, then legacy formats. Pair this with proper try_files logic to reflect the order of preference.

Security and Performance Notes

While serving optimized images is performance-oriented, don’t overlook security:

  • Set appropriate Content-Type headers so files aren’t interpreted as text or script.
  • Ensure files have proper file permissions and cannot be overwritten or deleted externally.
  • Leverage HTTP/2 or HTTP/3 to further optimize asset delivery.

Final Thoughts

Optimizing image delivery at the server level is one of the most impactful ways to enhance web performance. With Nginx’s powerful, yet efficient feature set—like map, try_files, and caching—you can deliver next-gen images selectively, automatically, and robustly.

These small enhancements deliver notable improvements in metrics like Largest Contentful Paint (LCP), bandwidth savings, and mobile responsiveness, all of which are critical for SEO and user satisfaction.

Deploying this solution today will future-proof your site and improve your overall infrastructure readiness for the modern web.

Image not found in postmeta