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

Case:

  • 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
                        keys_zone=image_cache:10m;

proxy_cache_path        /dev/shm/image_cache_webp
                        keys_zone=image_cache_webp:10m;

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

In your site config:

proxy_cache             $webp_pool;