Site icon NavThemes

Auto-Redirect to WebP/AVIF on Nginx (How-To)

With the rising popularity of web performance optimization, delivering images in modern formats such as WebP and AVIF has become an essential task for developers and server administrators. These image formats offer better compression and reduced file sizes without compromising image quality, resulting in faster page loads and better overall user experiences.

However, implementing these formats efficiently can be challenging, especially when serving websites through an Nginx server. In this guide, you’ll learn how to auto-redirect traditional image formats like JPEG and PNG to their lightweight WebP or AVIF equivalents on Nginx, tailoring content delivery based on browser support.

Why Use WebP and AVIF?

Both WebP and AVIF are next-generation image formats that drastically reduce image file sizes:

Using either format—or both—can dramatically speed up your website, particularly on image-heavy pages.

Step-by-Step Guide to Auto-Redirect Using Nginx

The approach centers around sniffing the browser’s Accept headers and rewriting URLs or serving appropriate files with Nginx’s configuration capabilities.

1. Prepare Your Image Files

Before you begin configuring Nginx, make sure you have converted your existing images (JPG, PNG, etc.) into WebP and/or AVIF. Useful tools include:

For example, to convert using ImageMagick:

convert image.jpg image.webp
convert image.jpg image.avif

Save these converted images with the same filename but different extensions in the same directory as your originals.

2. Understand Accept Headers

Modern browsers send the accepted formats in the HTTP Accept header. You can detect support for WebP or AVIF with these header strings:

Nginx can inspect these headers and serve the correct image format accordingly.

3. Configure Nginx for Auto-Redirect

You can implement format detection using Nginx’s map and try_files directives.

Setup Example:

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

    server {
        listen 80;
        server_name yourdomain.com;
        root /var/www/html;

        location ~* ^/images/(.*)\.(jpg|jpeg|png)$ {
            set $name $1;
            set $ext $2;

            try_files /images/$name$webp_suffix.$ext
                      /images/$name.$ext
                      =404;
        }
    }
}

Explanation:

4. Ensure the Order of Preference

In the example above, AVIF is given priority if the browser supports both formats. If AVIF isn’t available, WebP is used; otherwise, the original image is served. This flow can be customized depending on your preference or audience browser usage data.

Enhancing Performance with a CDN

If you use a Content Delivery Network (CDN), many popular CDNs such as Cloudflare or BunnyCDN support automatic image format conversion. However, if you’re running your own Nginx server, this manual setup is the way to go. You can still take advantage of CDN caching—ensure your CDN is set up to cache image variants appropriately by extension.

Use the Vary Header

Be mindful of caching when implementing file serving based on headers. Add the Vary: Accept header to responses to inform proxy caches and CDNs that different content may be served based on the Accept header. To configure this, add:

add_header Vary Accept;

Place this inside the appropriate location block in your Nginx config.

Fallback Handling and Testing

It’s essential to ensure fallback images are always available. During testing, use a browser’s developer tools to inspect image URLs and request headers. You can also use cURL:

curl -H "Accept: image/avif" https://yourdomain.com/images/sample.jpg -I
curl -H "Accept: image/webp" https://yourdomain.com/images/sample.jpg -I

This returns the headers of the requested URLs, so you can verify content-type and redirection behavior.

Troubleshooting Common Issues

Security Considerations

Always validate the request path and restrict variable-based file generation to safe directories. Avoid unvalidated user input directly affecting file paths. Here’s an enhanced secure variant:

location ~* ^/images/([a-zA-Z0-9_-]+)\.(jpg|jpeg|png)$ {
    set $name $1;
    set $ext $2;

    try_files /images/$name$webp_suffix.$ext
              /images/$name.$ext
              =404;

    add_header Vary Accept;
}

This example only accepts alphanumeric characters, hyphens, and underscores, minimizing file path abuse.

Summary

Delivering AVIF and WebP images using Nginx is a powerful way to optimize your site’s speed and performance with minimal server overhead. With just a few configuration changes, you can significantly reduce image load times and enhance user experience—especially on mobile and slower connections.

To recap, here’s what you’ve learned:

Once set up, your site can deliver the most efficient image format automatically, without changing a single image URL in your HTML or CSS. That’s performance power with elegance!

Exit mobile version