# 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.

URL: https://levelrail.com/learn/web-servers/gzip-and-caching-headers/
Updated: 2026-11-27

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](https://levelrail.com/learn/glossary/#nginx)), and they work the same over [HTTPS](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/glossary/#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](https://levelrail.com/learn/deploy-operate/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](https://levelrail.com/learn/web-servers/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

| 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

```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
```

## Related lessons

- [Nginx from scratch](https://levelrail.com/learn/web-servers/nginx-from-scratch/)): where these directives live.
- [Zero-downtime deploys](https://levelrail.com/learn/deploy-operate/zero-downtime-deploys/)): why old assets must outlive a release.
- [Nginx HTTPS with certbot](https://levelrail.com/learn/web-servers/nginx-https-with-certbot/)): serve all this over TLS.
- [Caddy from scratch](https://levelrail.com/learn/web-servers/caddy-from-scratch/)): Caddy's `encode gzip zstd` and `header` directives do the same job.
- [Nginx reverse proxy for a Node app](https://levelrail.com/learn/web-servers/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](https://levelrail.com/blog/self-host-static-site-docker/)): put hashed assets behind a container.

## Next

Protect the server from abusive clients with [rate limiting and security headers](https://levelrail.com/learn/web-servers/rate-limiting-and-security-headers/)).

## 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

- [Nginx docs, ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html)
- [Nginx docs, ngx_http_headers_module](https://nginx.org/en/docs/http/ngx_http_headers_module.html)
