Chapter 8 · Lesson 5 of 8
Web servers and proxies

Gzip and caching headers in nginx: Cache-Control, ETag, expires

Gzip shrinks text responses on the wire, and Cache-Control tells browsers how long to reuse a file, so long caching goes on hashed assets and never on index.html.

By the end you will

Enable gzip and set cache headers in nginx, then check both with curl -I and an Accept-Encoding header.

Time
22 min
Level
Intermediate
Check
4 questions
You need
  • An nginx site that already serves static files or an app
  • curl on your laptop or the server

Two small changes cut most of a static site’s transfer cost: compress text, and stop re-downloading files that did not change. Both are a few lines in nginx, and they work the same over HTTPS. The risk is caching the wrong file for too long, so this lesson spends as much time on what not to cache.

How it works#

When a browser asks for a file it sends Accept-Encoding: gzip, br. If nginx has gzip on and the type is in its list, it compresses the body, adds Content-Encoding: gzip and sends fewer bytes. Compression costs CPU and gains nothing on files already compressed, such as JPEG, PNG, WebP, MP4 and zip.

Caching is controlled by response headers. Cache-Control says how long a copy stays fresh. After that the browser revalidates using validators: ETag (a fingerprint) or Last-Modified (a date). The server answers 304 Not Modified with no body when nothing changed. Nginx adds both validators for static files on its own. The http status code 304 is the saving you want to see.

Step 1: Turn on gzip#

Put this in the http block of /etc/nginx/nginx.conf, or in a server block. On Ubuntu the stock nginx.conf already has a commented gzip section, so check for duplicates before adding lines (a repeated gzip on; at the same level fails nginx -t).

nginx
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
  • gzip on enables it. text/html is always compressed when it is on.
  • gzip_vary on adds Vary: Accept-Encoding so shared caches keep the right copy.
  • gzip_min_length 1024 skips tiny responses where gzip header overhead beats the gain.
  • gzip_comp_level 5 is a middle setting on a 1 to 9 scale. Higher costs more CPU for small extra savings.
  • gzip_types lists the MIME types to compress. Do not list images that are already compressed. SVG is text, so it is fine.

Apply it:

bash
sudo nginx -t && sudo systemctl reload nginx

When nginx sits in front of an app, gzip also applies to proxied responses, unless the app already compressed them.

Step 2: Cache hashed assets for a long time#

Build tools write files like app.3f9c2a.js, where the name changes whenever the content does. Those can be cached for a year:

nginx
location /assets/ {
    expires 1y;
    add_header Cache-Control "public, max-age=31536000, immutable";
}

expires 1y sets Expires and a matching max-age. The explicit Cache-Control adds immutable, which tells browsers not to revalidate on reload. If you set both, check the actual headers in Step 4 so you know which wins. Keeping only the add_header line is simplest.

Step 3: Never long-cache the HTML#

nginx
location = /index.html {
    add_header Cache-Control "no-cache";
}

no-cache is not “do not cache”. It means the browser may store the file but must revalidate with the server before using it, which costs a small 304 round trip. Use no-store only for private data you never want kept, such as account pages. HTML points at the hashed files, so a stale HTML file means users never see your new assets. This rule is the reason hashed filenames exist, and it connects to zero-downtime deploys, where old and new assets must both be around during a switch.

For files without a hash in the name (a logo, robots.txt), pick a short life, such as max-age=3600.

Step 4: Check with curl#

bash
curl -sI -H 'Accept-Encoding: gzip' https://example.com/assets/app.3f9c2a.js
curl -sI https://example.com/index.html

Look for Content-Encoding: gzip, Vary: Accept-Encoding, the Cache-Control value, and ETag and Last-Modified. To confirm revalidation, copy the ETag into curl -sI -H 'If-None-Match: "<etag>"' URL, which should return 304 Not Modified.

Check it worked#

Compare sizes:

bash
curl -s -o /dev/null -w '%{size_download}\n' https://example.com/assets/app.3f9c2a.js
curl -s -H 'Accept-Encoding: gzip' -o /dev/null -w '%{size_download}\n' https://example.com/assets/app.3f9c2a.js

The second number should be clearly smaller for a text file. Reload the page in the browser dev tools network tab and look at the “Size” column: assets show (disk cache) or 304 on a second visit, while the HTML still makes a request.

Edge cases and gotchas#

  • add_header in a location drops the server level ones. nginx does not inherit add_header into a block that defines its own. See rate limiting and security headers for the full rule.
  • Cached errors. A Cache-Control set with add_header is only added to 2xx and 3xx responses unless you add always, so error pages are not cached by accident.
  • Compressing already compressed files wastes CPU. Leave image/jpeg, image/png and video out of gzip_types.
  • Gzip and TLS. Compressing secret data that also reflects user input can leak it in some attacks (BREACH). It matters for pages that mix secrets with attacker-controlled text. Static assets are not affected.
  • A CDN or the app may compress already. If both do, you can end up with double work or a missing header. Pick one place.
  • Hash in the name only works with a build step. If you edit app.js in place and cache it for a year, users keep the old file. Use short caching for unhashed names.
  • Brotli is not in the stock package. nginx needs a separate module for it, so gzip is the plain default.

Troubleshooting#

SymptomLikely causeFix
No Content-Encoding in curl outputMissing Accept-Encoding header in the requestAdd -H 'Accept-Encoding: gzip'
Still no gzip headerType not in gzip_types, or body under gzip_min_lengthAdd the type, check the size
nginx: [emerg] "gzip" directive is duplicateAlready set at the same levelRemove one, or keep only the default section
Users see the old site after a deployindex.html cached too longUse no-cache on HTML, check the real headers
Browser never revalidates an assetimmutable or long max-ageChange the file name when the content changes
Two Cache-Control lines in the responseBoth the app and nginx add oneSet it in one place, or use proxy_hide_header Cache-Control
304 never appearsETag stripped or file changed each requestCheck the ETag header, avoid proxies that remove it
Large JSON is slow even with gzipLevel too high or app is the bottleneckTry a lower gzip_comp_level, profile the app

Quick reference#

nginx
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript image/svg+xml;

location /assets/ { add_header Cache-Control "public, max-age=31536000, immutable"; }
location = /index.html { add_header Cache-Control "no-cache"; }
bash
curl -sI -H 'Accept-Encoding: gzip' https://example.com/assets/app.3f9c2a.js
curl -sI https://example.com/index.html

Next#

Protect the server from abusive clients with rate limiting and security headers.

Check what you learned4 questions
1How do you ask a server for a gzip response with curl?
2Which Cache-Control value suits app.3f9c2a.js, a file whose name changes on every build?
3What does ETag let a browser do?
4Why add gzip_vary on;?

Frequently asked questions

How do I enable gzip in nginx?

Add gzip on; and a gzip_types list to the http or server block, then run nginx -t and reload. HTML is compressed by default once gzip is on, other types need to be listed.

What is the difference between no-cache and no-store?

no-cache lets the browser keep a copy but forces it to check with the server before using it. no-store tells caches not to keep the response at all.

How do I check if nginx gzip is working?

Run curl -sI -H 'Accept-Encoding: gzip' https://example.com/app.js and look for Content-Encoding: gzip in the headers.

Why should I not cache index.html for a year?

It points to your hashed asset files. If browsers keep an old copy, they keep asking for old assets and never see your new deploy.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios