Course contentsShow
← Web Development
Lesson 2149 of 2,98239. Network PerformanceFree lesson

Vary Header

Using Vary to cache different versions of a resource based on request headers.

Vary Header

What you'll learn: How to use the Vary header to cache different versions of the same resource based on incoming request headers.

The Problem of Multiple Versions

Imagine your server sends different content for the same URL depending on who's asking—maybe a compressed version for modern browsers, plain text for older ones, or different content based on the user's language preference. Without proper instructions, caches (both browser and CDN) might serve the wrong version to the wrong client.

What the Vary Header Does

The Vary header tells caching systems: "This response might differ based on specific request headers, so check those headers before serving a cached copy."

When your server responds with Vary: Accept-Encoding, it's saying "I might send different content based on whether the client accepts gzip, brotli, or no compression—cache separate versions for each."

Common Use Cases

Content negotiation: Vary: Accept-Encoding is the most common—cache separate compressed and uncompressed versions.

Internationalization: Vary: Accept-Language caches different language versions.

Device-specific content: Vary: User-Agent (use cautiously—creates many cache entries).

Multiple criteria: Vary: Accept-Encoding, Accept-Language checks both headers.

The Syntax

Vary: Accept-Encoding
Vary: Accept-Language
Vary: Accept-Encoding, User-Agent

How It Works

Without Vary, a cache stores: GET /api/data → [response]

With Vary: Accept-Encoding, a cache stores:

  • GET /api/data + Accept-Encoding: gzip → [gzipped response]
  • GET /api/data + Accept-Encoding: br → [brotli response]
  • GET /api/data + no encoding → [plain response]

Key Takeaway: The Vary header prevents caches from serving the wrong response variant by instructing them to consider specific request headers when matching cached entries.