gzip, gzip_static & Brotli
Text compresses well: HTML, CSS, JavaScript, JSON and SVG typically shrink to a fifth or less of their size. Compressing at the proxy saves bandwidth for every client and makes pages load faster on slow links, for a little CPU. The browser announces what it understands in Accept-Encoding (gzip, deflate, br, zstd), and the server answers with Content-Encoding.
gzip on the fly
Nginx's gzip module is off by default for proxied responses and only compresses text/html unless told otherwise. A sensible block:
gzip on;
gzip_comp_level 5; # 1 (fast) .. 9 (small); 4-6 is the usual sweet spot
gzip_min_length 1000; # tiny responses aren't worth it (default 20 bytes)
gzip_proxied any; # also compress responses to requests that came via another proxy (Via header)
gzip_vary on; # add "Vary: Accept-Encoding" so caches keep both versions
gzip_types text/css application/javascript application/json image/svg+xml text/plain application/xml;gzip_proxied matters when a CDN or load balancer sits in front: those requests carry a Via header, and with the default gzip_proxied off Nginx doesn't compress them at all. Don't add already-compressed types (image/png, image/jpeg, video/*, application/zip): compressing them again costs CPU and gains nothing.
mkdir -p www
python3 -c "
import json
rows = [{'id': i, 'name': f'product {i}', 'price': i * 1.25, 'tags': ['sale', 'new']} for i in range(400)]
print(json.dumps(rows))" > www/products.json
python3 -c "import random, sys; random.seed(7); sys.stdout.buffer.write(random.randbytes(20000))" > www/photo.jpg # incompressible, like a real JPEG
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
include /etc/nginx/mime.types;
gzip on;
gzip_comp_level 5;
gzip_min_length 1000;
gzip_vary on;
gzip_types application/json;
server { listen 127.0.0.1:8080; root www; }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
size() { curl -s -o /dev/null -w '%{size_download}' "$@"; }
echo "products.json identity: $(size 127.0.0.1:8080/products.json) bytes"
echo "products.json gzip: $(size -H 'Accept-Encoding: gzip' 127.0.0.1:8080/products.json) bytes"
echo "photo.jpg gzip: $(size -H 'Accept-Encoding: gzip' 127.0.0.1:8080/photo.jpg) bytes (not in gzip_types)"
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' 127.0.0.1:8080/products.json | grep -iE '^(content-encoding|vary|content-length|transfer-encoding)' | tr -d '\r'
curl -s --compressed 127.0.0.1:8080/products.json | python3 -c "import json,sys; print(len(json.load(sys.stdin)), 'products decoded fine')"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/nullproducts.json identity: 30693 bytes
products.json gzip: 3163 bytes
photo.jpg gzip: 20000 bytes (not in gzip_types)
Transfer-Encoding: chunked
Vary: Accept-Encoding
Content-Encoding: gzip
400 products decoded fine
The JSON shrank by about 90 % (30.7 kB to 3.2 kB); the random JPEG wasn't touched. Note the response headers: on-the-fly compression doesn't know the final size in advance, so the response uses Transfer-Encoding: chunked instead of Content-Length. curl --compressed sends Accept-Encoding and decompresses, which is what browsers do.
gzip_static: compress once at build time
Compressing the same app.js for every request wastes CPU. With gzip_static on;, Nginx looks for a precompressed app.js.gz next to the file and sends it as is to clients that accept gzip; others get the plain file. The build step produces the .gz files (and can use the slowest, best compression, since it runs once):
mkdir -p www/assets
python3 -c "print('function add(a, b) { return a + b; }\n' * 300)" > www/assets/app.js
gzip -9 -k -n www/assets/app.js
ls www/assets
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
include /etc/nginx/mime.types;
server {
listen 127.0.0.1:8080; root www;
location /assets/ { gzip_static on; gzip_vary on; expires 1y; }
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "on disk: app.js $(stat -c %s www/assets/app.js) bytes, app.js.gz $(stat -c %s www/assets/app.js.gz) bytes"
for enc in identity gzip; do
curl -s -D hdr.txt -o /dev/null -H "Accept-Encoding: $enc" 127.0.0.1:8080/assets/app.js
echo "Accept-Encoding: $enc -> $(grep -iE '^content-(length|encoding)' hdr.txt | tr -d '\r' | xargs)"
done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/nullapp.js
app.js.gz
on disk: app.js 11101 bytes, app.js.gz 107 bytes
Accept-Encoding: identity -> Content-Length: 11101
Accept-Encoding: gzip -> Content-Length: 107 Content-Encoding: gzip
The gzip client got the 107-byte precompressed file (the repetitive demo file compresses extremely well) with a real Content-Length, the other client the plain file, and Nginx compressed nothing at request time. gzip -n leaves the original name and timestamp out of the archive, so the .gz is reproducible. Remember to regenerate the .gz files whenever the originals change, or clients get stale code: build both in the same step.
Brotli and zstd
Brotli (br) compresses text 15–25 % better than gzip at similar speed and is supported by all current browsers, over HTTPS. Nginx has no built-in Brotli: it comes from the ngx_brotli module (Google), which Ubuntu's nginx 1.24 doesn't include, so it can't run in this sandbox. Some distributions package it as dynamic modules (search the package manager for brotli); otherwise you build the module against your exact Nginx version, or use a build of Nginx that ships it. Sample configuration:
# Sample: requires the ngx_brotli dynamic modules
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;
http {
brotli on;
brotli_comp_level 5;
brotli_types text/css application/javascript application/json image/svg+xml;
brotli_static on; # serve app.js.br when present, like gzip_static
gzip on; # keep gzip for clients without br
}Caddy has gzip and zstd built in (encode zstd gzip) and serves precompressed .br, .zst and .gz files with file_server { precompressed br zstd gzip }. Zstandard (zstd) is supported by Chromium-based browsers and Firefox; it compresses faster than Brotli at similar ratios. In the Caddyfile lesson the sandbox's curl negotiates it with Caddy for real.
Compression and secrets: BREACH
Compressing a response that contains both a secret (a CSRF token) and text the attacker controls (a reflected query parameter) over HTTPS can leak the secret through response sizes (the BREACH attack). Frameworks defend against it by masking CSRF tokens per response; you can also avoid compressing such pages. It is a reason not to enable compression blindly for every dynamic type.
Test yourself
Behind a CDN, Nginx stops compressing responses although gzip on; is set. What is the likely cause?
- CDNs block gzip
- The CDN's requests carry a
Viaheader andgzip_proxieddefaults to off - gzip_comp_level is too low
- The responses are too big
What does gzip_static on; do?
- Compresses static files on every request
- Serves a precompressed
file.gznext to the requested file to clients that accept gzip, without compressing at request time - Disables gzip for static files
- Creates .gz files on disk
Why is image/jpeg not in a good gzip_types list?
- Browsers can't decompress it
- JPEG is already compressed; gzip would cost CPU for no size gain
- It is a security risk
- Nginx refuses