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.
- Updated Nov 27, 2026
- Markdown
Enable gzip and set cache headers in nginx, then check both with curl -I and an Accept-Encoding header.
- 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).
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 onenables it.text/htmlis always compressed when it is on.gzip_vary onaddsVary: Accept-Encodingso shared caches keep the right copy.gzip_min_length 1024skips tiny responses where gzip header overhead beats the gain.gzip_comp_level 5is a middle setting on a 1 to 9 scale. Higher costs more CPU for small extra savings.gzip_typeslists the MIME types to compress. Do not list images that are already compressed. SVG is text, so it is fine.
Apply it:
sudo nginx -t && sudo systemctl reload nginxWhen 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:
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#
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#
curl -sI -H 'Accept-Encoding: gzip' https://example.com/assets/app.3f9c2a.js
curl -sI https://example.com/index.htmlLook 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:
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.jsThe 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_headerin alocationdrops the server level ones. nginx does not inheritadd_headerinto a block that defines its own. See rate limiting and security headers for the full rule.- Cached errors. A
Cache-Controlset withadd_headeris only added to 2xx and 3xx responses unless you addalways, so error pages are not cached by accident. - Compressing already compressed files wastes CPU. Leave
image/jpeg,image/pngand video out ofgzip_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.jsin 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#
| Symptom | Likely cause | Fix |
|---|---|---|
No Content-Encoding in curl output | Missing Accept-Encoding header in the request | Add -H 'Accept-Encoding: gzip' |
| Still no gzip header | Type not in gzip_types, or body under gzip_min_length | Add the type, check the size |
nginx: [emerg] "gzip" directive is duplicate | Already set at the same level | Remove one, or keep only the default section |
| Users see the old site after a deploy | index.html cached too long | Use no-cache on HTML, check the real headers |
| Browser never revalidates an asset | immutable or long max-age | Change the file name when the content changes |
Two Cache-Control lines in the response | Both the app and nginx add one | Set it in one place, or use proxy_hide_header Cache-Control |
304 never appears | ETag stripped or file changed each request | Check the ETag header, avoid proxies that remove it |
| Large JSON is slow even with gzip | Level too high or app is the bottleneck | Try a lower gzip_comp_level, profile the app |
Quick reference#
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"; }curl -sI -H 'Accept-Encoding: gzip' https://example.com/assets/app.3f9c2a.js
curl -sI https://example.com/index.htmlRelated lessons#
- Nginx from scratch: where these directives live.
- Zero-downtime deploys: why old assets must outlive a release.
- Nginx HTTPS with certbot: serve all this over TLS.
- Caddy from scratch: Caddy’s
encode gzip zstdandheaderdirectives do the same job. - Nginx reverse proxy for a Node app: when the app sets its own cache headers behind the proxy.
- Self-host a static site with Docker: put hashed assets behind a container.
Next#
Protect the server from abusive clients with rate limiting and security headers.
Check what you learned
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
Keep going: guides and tutorials
- Self-Hosted Static Site Hosting: Deploy a Folder With Levelrail Self-hosted static site hosting from a plain folder: one deploy command, _redirects, _headers and a custom 404 honored, plus a one command rollback.
- Deploy Next.js on a VPS With Docker, Git Push and HTTPS Deploy a Next.js app to your own VPS with Docker, a health check, HTTPS and rollback. Includes the NEXT_PUBLIC build trap that leaves variables empty.