Does WebP work with Varnish?

Does WebP work with Varnish?

WebP images are compatible with the Varnish cache. The compatibility was introduced to the module in version 2.1.2. Make sure that you have the latest version of the extension installed.


To make WebP images load on the website, it is required to adjust the Varnish configuration. Please contact your hosting provider on this matter or follow the steps below.

Step 1. Open the Varnish configuration fileUsually, it is placed here:

/usr/varnish/default.vcl

Step 2. Find the vcl_hash subroutine and paste this code to it:

# Amasty Google Page Speed Optimizer device detection and cache separation mechanism
    if (req.http.cookie !~ "X-Magento-Vary=") {
        call device_detect;

        if ((req.http.X-Amasty-Accept-Avif || req.http.X-Amasty-Accept-Webp) && req.http.X-Amasty-Device) {
            hash_data(req.http.X-Amasty-Accept-Avif);
            hash_data(req.http.X-Amasty-Accept-Webp);
            hash_data(req.http.X-Amasty-Device);
        }
    }

Step 3. Add a new subroutine using this code:

sub device_detect {
    unset req.http.X-Amasty-Accept-Webp;
    unset req.http.X-Amasty-Accept-Avif;
    unset req.http.X-Amasty-Device;

    if (req.http.Accept ~ "image\/webp" ||
        req.http.User-Agent ~ "(?i)(\biPhone|\biPod|\biPad|\bMacintosh).*Version\/(1[4-9]|[2-9][0-9])" ||
        req.http.User-Agent ~ "(?i)Edg|Firefox|Chrome|Opera"
    ) {
        set req.http.X-Amasty-Accept-Webp = "true";
    }
    
    if (req.http.Accept ~ "image\/avif" ||
    	req.http.User-Agent ~ "(?i)(?!.*Edg)(Firefox|Chrome|Opera)" ||
    	req.http.User-Agent ~ "(?i)(\bMacintosh).*Version\/(1[6-9].[4-9]|1[7-9]|[2-9][0-9])" ||
    	req.http.User-Agent ~ "(?i)(\biPhone|\biPod|\biPad).*Version\/(1[6-9]|[2-9][0-9])"
    ) {
        set req.http.X-Amasty-Accept-Avif = "true";
    }

    if (req.http.User-Agent ~ "(?i)Mobile") {
        set req.http.X-Amasty-Device = "mobile";
    } elsif (req.http.User-Agent ~ "(?i)Tablet") {
        set req.http.X-Amasty-Device = "tablet";
    } else {
        set req.http.X-Amasty-Device = "desktop";
    }
}

Step 4. Now restart Varnish and enjoy WebP images on your website.