Brotli Files on Disk, Gzip on the Wire
Every public text file on this site ships with two compressed copies next to it. index.html has an index.html.br and an index.html.gz, and so does every post, the stylesheet, the JavaScript bundles, the feed and the sitemaps. A small script in the repo makes them before deploy, and nginx is supposed to send whichever copy the browser can read.
For a while it didn’t. The Brotli module was installed on the server, but the line that turns it on, brotli_static on;, was still commented out in nginx.conf. Every browser that asked for Brotli got gzip instead. The .br files sat on disk and nothing ever read them. I uncommented it on 28 October 2026. The EC2 deploy post covers that fix in one short section, alongside four other deploy problems.
Here I go through what sits behind that one line. nginx has to pick foo.html.br or foo.html.gz for a request to foo.html, fall back when a sibling is missing, and tell caches about it with Vary. After that come the differences from gzip on, the choice of compression level, and the stale sibling, which is the one new way pre-compression can break a site. All byte counts and headers below come from the live site and the repo, measured on 17 November 2026. Where something comes from reading nginx or ngx_brotli source rather than from a test, I say so.
What Is on Disk
The site has no build step. It’s plain HTML, CSS and JS in a git repo, copied to the server with rsync. The only build-like step is scripts/compress.py, which keeps the .br and .gz siblings in sync with their sources. These are the parts of it that matter here:
TEXT_EXT = {".html", ".css", ".js", ".xml", ".txt", ".json", ".svg"}
PUBLIC_DIRS = ("css", "js", "pages", "posts", "images", "fonts", ".well-known")
def gzip_bytes(data: bytes) -> bytes:
buf = io.BytesIO()
# mtime=0 keeps the output byte-identical across runs (clean git diffs).
with gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=9, mtime=0) as f:
f.write(data)
return buf.getvalue()
def sibling_ok(path: Path, data: bytes, decode) -> bool:
if not path.exists() or path.stat().st_size == 0:
return False
try:
return decode(path.read_bytes()) == data
except Exception: # noqa: BLE001 - any decode error means "rewrite it"
return False
def compress_file(src: Path, check: bool = False) -> list[str]:
data = src.read_bytes()
changed = []
for ext, encode, decode in (
(".gz", gzip_bytes, gzip.decompress),
(".br", lambda d: brotli.compress(d, quality=11), brotli.decompress),
):
sib = src.with_name(src.name + ext)
if sibling_ok(sib, data, decode):
continue
changed.append(sib.relative_to(ROOT).as_posix())
if not check:
sib.write_bytes(encode(data))
return changedMost of the choices in there are deliberate:
- Only text types get compressed:
.html,.css,.js,.xml,.txt,.jsonand.svg. PNG, WebP and WOFF2 are already compressed, and running gzip over them saves next to nothing. - It looks at the root files plus
css/,js/,pages/,posts/,images/,fonts/and.well-known/, the same set the deploy allowlist ships. Private folders (nginx/,services/,scripts/,.claude/) and dotfiles in the root are skipped, so a config file never gets a public.gztwin by accident. - Gzip runs at level 9, the maximum, with
mtime=0so the output is byte-identical every time and git only sees a change when the content changed. Brotli runs at quality 11, also the maximum. - To decide whether a sibling is current, it decompresses the existing
.bror.gzand compares the result byte for byte with the source. Timestamps play no part. A sibling that is missing, empty, corrupt or decodes to different bytes gets rewritten. - A
.bror.gzwhose source no longer exists is an orphan and gets deleted. In--checkmode it’s only reported.
Here is what that looks like for three files in the repo. Sizes are in bytes:
ls -lgo index.html* css/style.f625664f.css* posts/nginx-configuration.html*
The homepage is 38,370 bytes as HTML, 8,886 as gzip and 7,242 as Brotli. The siblings add disk space, but not much. All the .gz files together come to 758,261 bytes and all the .br files to 611,247, next to 3,066,444 bytes of sources. That’s about 45% more on disk, to save around 80% on the wire.
The nginx Config
The compression part of the repo’s nginx/nginx.conf is short. The static directives come first, then an on-the-fly gzip fallback:
# Compression (pre-compressed .br/.gz already on disk)
# Static (preferred — files were precompressed by build):
gzip_static on;
brotli_static on; # module loaded via modules-enabled/50-mod-http-brotli-static.conf
# On-the-fly fallback (only for content not precompressed):
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_disable "msie6";
gzip_types
application/javascript
application/json
application/rss+xml
application/xml
image/svg+xml
text/css
text/plain; # trimmed here; the repo file lists 24 types
# ngx_brotli (uncomment whole block if module is loaded)
# brotli on;
# brotli_comp_level 6;The repo file only says what I meant the server to run, so I checked what it actually runs. nginx -T prints the full loaded config, includes and all, and changes nothing. Filtering out comment lines shows only the directives that are live:
sudo nginx -T 2>/dev/null | grep -nE 'brotli|gzip' | grep -vE '^[0-9]+: *#'
Both static directives are on, in the http block. That makes them apply to every server and location unless one turns them off. Both brotli_static and gzip_static are valid in http, server and location context, and both default to off. Forgetting either one means nginx never even looks for the sibling.
The Brotli module on the server is only the static half. The server runs nginx 1.28.3 from Ubuntu’s packages, with the Brotli module from the libnginx-mod-http-brotli-static package. The only Brotli file in /usr/lib/nginx/modules/ is ngx_http_brotli_static_module.so. The ngx_brotli project has two modules: a static one that serves .br files from disk, and a filter that compresses responses on the fly. Only the first is installed here. That’s why the brotli on; block stays commented out: without the filter module loaded, nginx rejects brotli as an unknown directive. Anything without a .br on disk can never go out as Brotli.
The gzip on lines are the fallback. When neither sibling is used, nginx can still gzip the response itself, if the type is listed in gzip_types and the response is at least gzip_min_length bytes. More on that below.
How nginx Picks foo.html.br or foo.html.gz
When a request for /posts/nginx-configuration.html reaches a location that serves files, nginx runs its content handlers in order. The Brotli static handler goes first, then the gzip static handler, then the plain static file handler. Each one either sends a response or declines and passes the request on.

I read the ngx_brotli source (static/ngx_http_brotli_static_module.c) to see exactly what the first handler checks. It runs only for GET and HEAD and skips URIs that end in /. It searches the Accept-Encoding header for a standalone br token, so brotli or xbr doesn’t count. Then it maps the URI to a path on disk with .br appended and tries to open it. If the file opens, nginx sends it with Content-Encoding: br and a Content-Length equal to the size of the .br file.
The gzip static handler in nginx itself (ngx_http_gzip_static_module.c) does the same with .gz, with one difference. It asks ngx_http_gzip_ok() whether this request may get gzip at all, and that function applies gzip_http_version, gzip_proxied and gzip_disable as well as the Accept-Encoding header. The Brotli handler applies none of those.
The ngx_brotli parser is simpler than the HTTP spec. It only declines br when the header gives it an explicit zero weight (br;q=0). It never compares weights between encodings, and it doesn’t treat * as a match. I tested that against the live homepage with five headers:
for ae in 'gzip, deflate, br, zstd' 'gzip;q=1.0, br;q=0.5' 'br;q=0, gzip' 'deflate' 'identity'; do
printf '%-26s ' "[$ae]"
curl -s -o /dev/null -D - -H "Accept-Encoding: $ae" https://codertronix.com/ | tr -d '\r' \
| awk -F': ' 'tolower($1)=="content-encoding"{e=$2} tolower($1)=="content-length"{l=$2} END{print (e?e:"identity"), l}'
done
gzip;q=1.0, br;q=0.5 says "I prefer gzip", and nginx still sends Brotli. In practice that rarely matters, because Chrome, at least, sends no weights. It sends gzip, deflate, br, zstd. But if you write a test client that relies on q-values, it won’t get what you expect. deflate on its own gets the uncompressed file, because nothing on disk is deflate-encoded.
The difference in which checks each handler makes shows up with HTTP/1.0 and with proxies:
# HTTP/1.0 asking for gzip, HTTP/1.0 asking for br, then gzip through a "proxy"
curl -s -0 -o /dev/null -D - -H 'Accept-Encoding: gzip' https://codertronix.com/ | grep -iE '^content-(length|encoding)' | tr -d '\r'
echo --
curl -s -0 -o /dev/null -D - -H 'Accept-Encoding: br' https://codertronix.com/ | grep -iE '^content-(length|encoding)' | tr -d '\r'
echo --
curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' -H 'Via: 1.1 test-proxy' https://codertronix.com/ \
| grep -iE '^content-(length|encoding)' | tr -d '\r'
An HTTP/1.0 request asking for gzip got the full 38,370-byte page. gzip_http_version defaults to 1.1, so the gzip static handler declined. The same HTTP/1.0 request asking for br got the 7,242-byte Brotli file, because the Brotli handler doesn’t check the HTTP version. The third request carries a Via header, which is how nginx recognises a proxied request. It still got gzip, because this config sets gzip_proxied any. With the default, off, a request through a proxy that adds Via would never get the .gz.
One more detail from the site config: pretty URLs work too. The main location uses try_files $uri $uri.html $uri/index.html $uri/ =404;, so /posts/nginx-configuration is served from nginx-configuration.html. The static handlers see the rewritten path, so that request also comes back as Brotli, at the same 14,155 bytes.
What Happens When a Sibling Is Missing
Both handlers treat "file not found" the same way. In the source, ENOENT, ENOTDIR and ENAMETOOLONG just return NGX_DECLINED, and the next handler runs. Nothing is written to the error log. A missing sibling therefore produces a bigger response with no error page and no log line.
The fallbacks depend on which file is missing:
- If only the
.bris missing, Brotli-capable browsers get the.gz. Chrome asks for Brotli on every HTTPS request (tested further down), so Chrome visitors all get the bigger file. On this site the gzip copy is 19 to 27% larger than the Brotli one (measured further down). - If only the
.gzis missing, Brotli browsers are fine. Clients that only take gzip get the plain file, which the on-the-flygzip onthen compresses at level 6, costing CPU on every request. - If both are missing, Brotli is gone for that file, because there’s no on-the-fly Brotli module, and gzip happens per request.
- If both are missing and the file is small or of an unlisted type, it goes out uncompressed.
This site has two real cases of the last kind. /ads.txt is served from /var/www/shared rather than the site folder (the EC2 post explains why), and that folder has no siblings. The comments API at /api/comments is a Go service behind nginx, so there’s no file on disk at all. Both responses are below gzip_min_length 1024, so neither gets compressed:
for u in /ads.txt '/api/comments?slug=nginx-configuration' /index.html.br; do
echo "== $u"
curl -s -o /dev/null -D - -H 'Accept-Encoding: br, gzip' "https://codertronix.com$u" \
| grep -iE '^(content-type|content-length|content-encoding|vary)'
done | tr -d '\r'
59 bytes of ads.txt and 55 bytes of JSON aren’t worth compressing, so that’s fine. The third request shows something else. If you ask for /index.html.br directly, nginx serves the raw Brotli bytes as application/octet-stream, with no Content-Encoding. Browsers will never request that URL by themselves. But it does mean siblings are public URLs, which is one more reason the script refuses to compress anything outside the public folders.
Because nginx says nothing when a sibling is missing, I checked the server for gaps directly. This read-only loop lists every public text file in the webroot that lacks either sibling:
# on the server, read-only: list public text files that lack a .gz or .br sibling
cd /var/www/codertronix.com
find . -type f \( -name "*.html" -o -name "*.css" -o -name "*.js" -o -name "*.xml" \
-o -name "*.txt" -o -name "*.json" -o -name "*.svg" \) |
while read -r f; do
[ -e "$f.gz" ] && [ -e "$f.br" ] || echo "missing sibling: $f"
done; echo "done, exit $?"It printed nothing but the final line, so every text file in the webroot has both siblings. That holds as long as compress.py has run before the deploy, because the deploy allowlist ships the .br and .gz files along with their sources.
Why Vary: Accept-Encoding Matters
Pre-compression means one URL now has three different bodies. Browsers, CDNs and proxy caches store responses by URL, so they need to know that the body depends on the request’s Accept-Encoding. That’s the job of the Vary header. MDN’s compression guide puts it plainly: when content negotiation picks the encoding, the server must send a Vary header containing at least Accept-Encoding, so that caches can store the different versions separately.
Here’s a real Brotli response from this site:
curl -sI -H 'Accept-Encoding: br' https://codertronix.com/posts/nginx-configuration.html \
| grep -iE '^(HTTP|content-type|content-length|content-encoding|vary|etag|last-modified|cache-control)' | tr -d '\r'
Without Vary, a shared cache could store that Brotli body and later hand it to a client that never asked for Brotli: an old script, a monitoring check, or any HTTP/1.0 client. That client would get bytes it can’t decode. There’s no CDN in front of this site today (the Server: nginx header comes straight from the origin), but the browser’s own cache follows the same rules, and a CDN could be added later without anyone remembering this.
The Brotli module never writes the Vary header itself. It sets a flag on the request (r->gzip_vary = 1), and nginx’s header filter adds Vary: Accept-Encoding only when that flag is set and gzip_vary on is configured for the location. The directive has "gzip" in its name, but it also controls Vary for Brotli responses. Leave it off and your .br responses go out with no Vary at all.
Even the uncompressed response carries Vary on this site, because the gzip static handler sets the flag as soon as it finds the .gz on disk, even when the client then can’t take gzip. That’s correct: the plain response is also one choice out of three.
Each variant also gets its own validators, because nginx builds ETag and Last-Modified from whichever file it actually sends:
for e in br gzip identity; do
echo "== $e"
curl -s -D - -o /dev/null -H "Accept-Encoding: $e" https://codertronix.com/posts/nginx-configuration.html \
| grep -iE '^(content-length|content-encoding|etag|last-modified)'
done | tr -d '\r'
Three ETags, one per file, so a cache revalidating its Brotli copy never gets told that the gzip copy is "the same". The Last-Modified values show a small wart. The nginx docs recommend giving the original and compressed files the same modification time. compress.py doesn’t copy the source’s mtime onto the siblings, so here the siblings are four seconds newer than the HTML. That’s harmless with Vary in place, but if you write your own compression script it’s worth copying the mtime across with os.utime.
Static Pre-Compression vs gzip on
A browser can’t tell the two apart. The server does very different work for each.
gzip on compresses each response as it is sent. It works on any response, including proxied ones and files you forgot about, and needs no build step. The cost is CPU on every request, and the level you can afford is limited by that. nginx’s default gzip_comp_level is 1, and this site uses 6. It also has a list of types to compress (text/html is always included), and a minimum length that is checked against the response’s Content-Length.
gzip_static and brotli_static do no compression at all while serving. They swap one file for another. That means zero compression CPU per request, a correct Content-Length straight from the file size, and range requests (the gzip static handler sets allow_ranges in the source). Most importantly, you can compress at the maximum level, because the slow work happens once, before deploy.
The costs of pre-compression are the ones already shown above. The siblings take about 45% more disk space. There’s a script to run. And there’s a new way to break the site: a sibling that no longer matches its source. That gets its own section below.
The two aren’t exclusive, and this config runs both. Static siblings handle every file that has them, and gzip on covers anything that doesn’t. For a static site the fallback almost never runs, because everything large enough to compress has siblings. If you’d rather know when it runs than have it cover gaps without telling you, the scan in the previous section tells you that directly.
Bytes on the Wire, Measured
When I turned Brotli on in October, I measured the Brotli versions of two of this site’s pages at about 18 to 19% smaller than gzip. Rather than repeat those numbers, I measured again from outside, asking for each encoding in turn. %{size_download} is the number of body bytes curl actually received, before decoding:
for u in / /posts/spring-boot-rest-api.html /css/style.f625664f.css /js/main.f66efe8e.js /feed.xml; do
for e in br gzip identity; do
curl -s -o /dev/null -H "Accept-Encoding: $e" -w "%{size_download}\t" "https://codertronix.com$u"
done; echo "$u"
done
| URL | Identity | gzip | Brotli | Brotli vs gzip |
|---|---|---|---|---|
Homepage / | 38,370 | 8,886 | 7,242 | 18.5% smaller |
Long post (spring-boot-rest-api.html) | 88,937 | 18,164 | 14,289 | 21.3% smaller |
Stylesheet (style.f625664f.css) | 113,564 | 22,146 | 18,178 | 17.9% smaller |
Main bundle (main.f66efe8e.js) | 77,695 | 21,967 | 18,522 | 15.7% smaller |
feed.xml | 21,015 | 4,662 | 3,808 | 18.3% smaller |
Today’s range is 16 to 21%, lower than the October figure. The pages have changed since then, so the table is the number I’d quote now. Both encodings remove most of the bytes: gzip saves 72 to 81% against the raw file, and Brotli takes off roughly another fifth of what’s left.

Smaller numbers only help if the content is the same. To make sure no sibling was serving a different version of the page, I fetched one post in all three encodings, decoded each body and hashed it:
# /// script
# requires-python = ">=3.10"
# dependencies = ["brotli==1.1.0"]
# ///
import gzip, hashlib, sys, urllib.request
import brotli
url = sys.argv[1]
def get(enc):
req = urllib.request.Request(url, headers={"Accept-Encoding": enc, "User-Agent": "sibling-check/1.0"})
with urllib.request.urlopen(req) as r:
return r.headers.get("Content-Encoding") or "identity", r.read()
for enc in ("br", "gzip", "identity"):
ce, raw = get(enc)
body = brotli.decompress(raw) if ce == "br" else gzip.decompress(raw) if ce == "gzip" else raw
print(f"{enc:<9} wire={len(raw):>6} decoded={len(body):>6} sha256={hashlib.sha256(body).hexdigest()[:16]}")uv run -q bench/samebody.py https://codertronix.com/posts/nginx-configuration.html
The wire sizes differ and the decoded bodies hash the same. The stale-sibling check below is what keeps it that way from one deploy to the next.
Compression Levels: Why Max Is Fine Here
With on-the-fly compression, the level is a trade between CPU per request and bytes per request. With pre-compression, it’s a trade between bytes and build time, and build time is cheap. To put numbers on it, I compressed four real site files at several levels with the same Python libraries compress.py uses, and timed compression and decompression on my development machine:
# /// script
# requires-python = ">=3.10"
# dependencies = ["brotli==1.1.0"]
# ///
import gzip, io, sys, time
from pathlib import Path
import brotli
repo = Path(sys.argv[1])
files = ["index.html", "posts/spring-boot-rest-api.html", "css/style.f625664f.css", "js/main.f66efe8e.js"]
def gz(d, lvl):
b = io.BytesIO()
with gzip.GzipFile(fileobj=b, mode="wb", compresslevel=lvl, mtime=0) as f:
f.write(d)
return b.getvalue()
def best(fn, n=5): # fastest of n runs, in ms
t = 1e9
for _ in range(n):
s = time.perf_counter(); out = fn(); t = min(t, time.perf_counter() - s)
return out, t * 1000
for name in files:
d = (repo / name).read_bytes()
print(f"## {name} {len(d)} bytes")
print(f"{'level':<8}{'bytes':>7}{'comp ms':>9}{'decomp ms':>11}")
rows = [(f"gzip -{l}", lambda l=l: gz(d, l), gzip.decompress) for l in (1, 6, 9)]
rows += [(f"br q{q}", lambda q=q: brotli.compress(d, quality=q), brotli.decompress) for q in (1, 4, 6, 9, 11)]
for label, comp, dec in rows:
out, ct = best(comp)
_, dt = best(lambda: dec(out))
print(f"{label:<8}{len(out):>7}{ct:>9.1f}{dt:>11.2f}")uv run -q levels.py "$SITE" | head -20

The CSS and JS files followed the same pattern as the two pages shown.
Gzip barely improves past level 6. Level 9 is 0.5% smaller than 6 on both pages shown. Using 9 costs nothing at build time, but it isn’t where the gains are.
Brotli is the opposite: its last step is the big one. Going from quality 6 to quality 11 makes the files 11 to 12% smaller across all four. Quality 9 is only a little better than 6. Most of Brotli’s advantage over gzip comes from quality 11. That level is also 33 to 46 times slower than 6 here: 58 ms instead of 1.3 ms for the long post. Spent per request, that’s a real cost. ngx_brotli’s own brotli_comp_level defaults to 6 for that reason. Spent once at build time, 58 ms is nothing.
Decompression didn’t get slower at higher levels. Decoding stayed between 0.03 and 0.23 ms at every level, so the browser pays nothing extra for quality 11.
Recompressing the whole site from scratch, all 68 sources and 136 siblings, took about 3 seconds on my machine in a scratch copy of the files, including uv starting up. The check-only pass, which decompresses and compares instead of compressing, took about 0.2 seconds. At those times there’s no reason to use anything below the maximum.
The Stale Sibling Problem
Pre-compression brings one new failure. nginx picks a sibling by file name alone. It doesn’t compare contents or timestamps. If I edit posts/page.html and deploy without rerunning compress.py, the old .br and .gz are still there, and nginx happily serves them.

Browsers ask for compression, so readers get the old page. A curl without an Accept-Encoding header gets the new HTML, so a quick check from the terminal says the fix is live.
That’s why compress.py has a --check mode that writes nothing and exits 1 on any mismatch. I reproduced the failure in a scratch folder, with a copy of the script and a two-line page, not in the real repo:
# in a scratch folder holding a copy of scripts/compress.py, not the real repo
printf '<!DOCTYPE html>\n<title>Sample</title>\n<p>Version 1 of this page.</p>\n' > posts/sample.html
uv run -q scripts/compress.py # make the siblings
sed -i 's/Version 1/Version 2/' posts/sample.html # edit the page, forget to recompress
uv run -q scripts/compress.py --check; echo "exit $?"
uv run -q scripts/compress.py # fix it
uv run -q scripts/compress.py --check; echo "exit $?"
After the edit, --check names both stale siblings and exits 1. After a normal run it reports nothing and exits 0. Because it compares decoded bytes instead of timestamps, it also catches the cases a timestamp check misses: a file copied with its old mtime kept, a checkout that touched every file, or a sibling that was truncated during upload. It also reports orphans, siblings whose source was deleted or renamed. nginx would never serve those for a real page, but they are still public URLs serving content that no longer exists anywhere else.
On the real repo with a clean tree, it reports:
uv run -q scripts/compress.py --check; echo "exit $?"
The exit code is what makes it useful. Put it at the start of a deploy script, or in a pre-push hook, and a stale sibling stops the deploy before readers see it. When you test by hand, send -H 'Accept-Encoding: br'. Without it, curl gets the plain file, which no browser is served.
Browsers Only Ask for Brotli over HTTPS
Browsers generally advertise br only on HTTPS connections. None of the docs I checked (MDN’s Accept-Encoding page, MDN’s Brotli glossary entry and caniuse) state this outright, so I tested it in Chrome. I loaded a public header-echo page, httpbin.org/headers, in Chrome 157 (driven by Playwright), once over each scheme:
- Over
http://, Chrome sentAccept-Encoding: gzip, deflate. - Over
https://, it sentAccept-Encoding: gzip, deflate, br, zstd.
On this site it makes little practical difference, because plain HTTP requests for pages get a 301 to HTTPS. (The exception is /ads.txt, which answers on HTTP directly, and that file has no siblings anyway.) But if you test pre-compression on a dev server over plain HTTP, the browser’s network tab will show gzip even though brotli_static works. Test with curl and an explicit header instead, since curl sends exactly the header you give it, over either scheme. The nginx configuration guide covers setting up TLS if your test server doesn’t have it yet.
Checklist
If you’re adding pre-compressed files to your own nginx setup, this is the short version:
gzip_static on;andbrotli_static on;are both set, andnginx -Ton the server shows them without a#in front.gzip_vary on;is set, since it also controlsVaryfor Brotli responses. Check forVary: Accept-Encodingwithcurl -sI -H 'Accept-Encoding: br'.- A request with
Accept-Encoding: brgetsContent-Encoding: brand aContent-Lengthequal to the size of the.brfile. - Siblings are compressed at maximum level (gzip 9, Brotli 11), because the cost is paid once.
- Every public text file has both siblings. Scan the webroot, because nginx doesn’t log a missing one.
- A content check like
compress.py --checkruns before every deploy and stops it on a non-zero exit. - Decoded bodies are identical for all three encodings.
- Browser tests run over HTTPS, and terminal tests send an explicit
Accept-Encodingheader.



