The HTTP Vary header tells caches and CDNs which request headers affect the response. Many sites historically used Vary: User-Agent, but this causes cache fragmentation and inefficiency. A better practice is to use Vary: Accept-Encoding, which ensures clients receive the correct compressed or uncompressed version of a resource.
Why Switch to Accept-Encoding
Using Vary: Accept-Encoding helps reduce risks of serving mismatched content. It ensures:
- Correct delivery of gzip, Brotli, or uncompressed files.
- Better cache efficiency compared to varying by user agent.
- Stronger performance and fewer decoding errors.
Apache Configuration
Enable headers and compression modules, then add:
<IfModule mod_headers.c>
Header append Vary: Accept-Encoding
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
Header append Vary: Accept-Encoding
</IfModule>
Restart Apache and check with:
curl -I https://yourdomain.com
You should see Vary: Accept-Encoding in the response headers.
NGINX Configuration
Add to your server block:
gzip on;
gzip_types text/html text/plain text/css application/javascript application/json;
add_header Vary Accept-Encoding;
Reload NGINX to apply changes.
Considerations
- Cache systems may create multiple entries if clients send different
Accept-Encoding strings. Normalization at the CDN level helps reduce this.
- Only your server responses can be controlled; third-party resources may not include the header.
Join The Discussion
Have you updated your server to use Vary: Accept-Encoding instead of User-Agent? Share whether it improved caching efficiency or caused issues with proxies and CDNs.