Proxying and Caching WebP Images Using the Same URI Based on User Accept Headers with Nginx


  • The proxied image backend serves WebP images when the client requests support it with Accept headers ($http_accept)
  • The backend also provides the same URI for all WebP requests. That means URI like image.png can also be in WebP format

The solution:

  • Using Nginx map module
  • Apply variables to different cache pools

In nginx.conf:

# Proxy cache pools for image caching
proxy_cache_path        /dev/shm/image_cache

proxy_cache_path        /dev/shm/image_cache_webp

# Differenate WebP requests
map $http_accept $webp_pool {
  default                 image_cache;
  ~*webp                  image_cache_webp;

In your site config:

proxy_cache             $webp_pool;