Compressing assets with Brotli on every CDN cache miss costs your origin CPU, and Brotli’s best quality level is far too slow to run per request. The fix is to serve pre-compressed Brotli and gzip files on Nginx: build .br and .gz copies once, and let brotli_static and gzip_static send them with no compression work at request time. At the end, curl will confirm each client gets the right file.
Quick answer: Install the Nginx Brotli module and create .br and .gz copies next to each asset at build time, keeping the originals. Then turn on brotli_static on;, gzip_static on; and gzip_proxied any;. Nginx then picks the right file from each request’s Accept-Encoding header.
- On Ubuntu 24.04 or newer, install
libnginx-mod-http-brotli-filterandlibnginx-mod-http-brotli-static. - Run
brotli --bestandgzip -9 -kover your built CSS, JS, SVG and JSON files. - Add the static and fallback compression directives to the server block.
- Run
sudo nginx -t, then reload. - Check with
curl -I -H "Accept-Encoding: br": the response should includeContent-Encoding: br.
In this guide
- Before You Start
- The CPU Cost of Dynamic Compression Behind a CDN
- Installing ngx_brotli on Ubuntu and Debian
- Generating Pre-Compressed Assets in Your Build Script
- Configuring Nginx with brotli_static and gzip_static
- The Gotcha: Accept-Encoding and ETags Behind a CDN
- Testing Origin Responses with cURL
- Handling Font Assets and Cross-Origin Rules
- Comparing Payload Sizes on Your Own Bundle
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps

Before You Start
- Server access: SSH with
sudoon the Nginx server. The package route needs Ubuntu 24.04 or newer (or current Debian); on Ubuntu 22.04 you need an Nginx build that includes the module. - Build access: the ability to add a step to your frontend build or CI, or to run a script on the server after each deploy.
- Time: about 20–30 minutes.
- Back up first: copy
/etc/nginx/nginx.confand your site file before editing, and runsudo nginx -tbefore every reload. An unknown directive or missing module makes the test fail, and the running site keeps its old configuration until you fix it.
The CPU Cost of Dynamic Compression Behind a CDN
The usual shortcut is to add brotli on; to nginx.conf, set the quality level to 4 or 5 so the server keeps up, and let the CDN handle the rest. That creates two problems.
First, quality level 5 produces noticeably larger files than level 11. Second, whenever your CDN purges or hits edge misses across different points of presence (PoPs), your origin eats the bill. If ten CDN nodes request your main bundle at once, your origin runs ten separate on-the-fly Brotli compressions in parallel.
Pre-compression flips this around. You compress your CSS, JS and SVG files once, ahead of time, at the highest settings (Brotli quality 11, gzip level 9 or Zopfli). When a request arrives, Nginx reads its Accept-Encoding header (the list of compression formats the client can decode) and looks on disk for a matching .br or .gz file. If one exists, Nginx sends it as is, with no compression work.
Installing ngx_brotli on Ubuntu and Debian
Nginx ships with ngx_http_gzip_static_module baked in on almost every Linux distro. Brotli isn’t as simple. The official Nginx mainline and stable builds don’t include Google’s ngx_brotli module unless you compile it manually or grab it from a repository that packages dynamic modules.
On Ubuntu 24.04 and newer, the distribution’s own archive packages the module for the distro Nginx (current Debian carries the same packages). Ubuntu 22.04’s archive does not; there you need an Nginx build from a repository that ships the module, or you compile it yourself.
On the server, update your package index and install the two module packages:
sudo apt update
sudo apt install libnginx-mod-http-brotli-filter libnginx-mod-http-brotli-static -yThe packages drop their load_module snippets into /etc/nginx/modules-enabled/, which the stock nginx.conf already includes, so nothing else is needed. If you compiled the module yourself instead, load it by hand at the very top of your /etc/nginx/nginx.conf file:
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;Always verify the syntax before reloading:
sudo nginx -t
sudo systemctl reload nginxYou should see syntax is ok and test is successful; only reload after that. To confirm the modules are loaded, run ls /etc/nginx/modules-enabled/ and look for the two Brotli entries.
Generating Pre-Compressed Assets in Your Build Script
For Nginx to serve pre-compressed files, they must sit alongside your uncompressed files in the exact same directory. When Nginx looks for app.js, it expects to find app.js.br and app.js.gz right next to it.
You can run this in CI/CD or directly on the server right after your frontend build finishes. The script below creates both formats at maximum compression and skips files that haven’t changed since their last compressed copy. Save it as, for example, compress-assets.sh, set TARGET_DIR to your build folder, and run it with bash compress-assets.sh. It needs the brotli command-line tool (sudo apt install brotli):
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="/var/www/my-app/dist"
# Compress with Gzip (level 9)
find "$TARGET_DIR" -type f '(' -name '*.js' -o -name '*.css' -o -name '*.svg' -o -name '*.json' -o -name '*.html' ')' | while read -r file; do
if [ ! -f "${file}.gz" ] || [ "$file" -nt "${file}.gz" ]; then
gzip -9 -k -f "$file"
fi
done
# Compress with Brotli (level 11)
find "$TARGET_DIR" -type f '(' -name '*.js' -o -name '*.css' -o -name '*.svg' -o -name '*.json' -o -name '*.html' ')' | while read -r file; do
if [ ! -f "${file}.br" ] || [ "$file" -nt "${file}.br" ]; then
brotli --best --force --keep "$file"
fi
doneThe -nt test (“newer than”) means only files newer than their existing compressed copies are processed. Afterwards, ls in the folder should show app.js, app.js.gz and app.js.br side by side. If you build with Vite, you can wire this directly into your build step using vite-plugin-compression2 (version 2 syntax shown; version 1 took a single algorithm option per plugin call):
import { defineConfig } from 'vite';
import { compression } from 'vite-plugin-compression2';
export default defineConfig({
plugins: [
compression({
algorithms: ['gzip', 'brotliCompress'],
deleteOriginalAssets: false
})
]
});Make sure deleteOriginalAssets stays false. Older clients, monitoring bots, and simple curl calls without an Accept-Encoding header still need that raw, uncompressed file or they’ll hit a 404.
Configuring Nginx with brotli_static and gzip_static
Once the files are on disk, update your site’s server block. You want both static modules on, plus long cache headers for fingerprinted files; our guide to immutable Cache-Control and cache busting in Nginx behind a CDN explains those headers in detail.
Here is a server block for serving pre-compressed assets behind a CDN. Adjust server_name and root to your site:
server {
listen 80;
server_name assets.example.com;
root /var/www/my-app/dist;
# Enable static module checks
gzip_static on;
brotli_static on;
# Fallback dynamic compression for files generated on the fly
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_proxied any;
gzip_comp_level 6;
brotli on;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;
brotli_comp_level 5;
location ~* \.(?:css|js|svg|json|wasm)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Vary "Accept-Encoding" always;
access_log off;
try_files $uri =404;
}
}With gzip_static on; and brotli_static on;, Nginx inspects the incoming Accept-Encoding header and serves the .br file to clients that accept Brotli, the .gz file to clients that only accept gzip, and the raw file to everyone else. Don’t use the always value here: it sends the compressed file to every client without checking whether it can decode it. Keep gzip_proxied any; too. Without it, Nginx refuses to serve gzip, static or dynamic, to requests that arrive with a Via header, which is exactly what a CDN adds. And the one-year immutable policy assumes fingerprinted filenames; shorten it for files that keep their name between deploys.
The Gotcha: Accept-Encoding and ETags Behind a CDN
If cache hits at the edge come back uncompressed (or gzip-only) even though the .br files are sitting on disk, the origin is usually not the problem. The request the CDN sends it is.
Nginx picks the variant purely from the Accept-Encoding header it receives; the MDN Content-Encoding documentation covers how that negotiation works. If your CDN strips Accept-Encoding when forwarding requests to the origin, or normalizes it to gzip only, Nginx never sees br and falls back to the .gz or raw .js file, which the CDN then caches.
ETags are the other surprise. Each pre-compressed file gets its own strong ETag, built from that file’s modification time and size, so the .br, .gz, and raw variants of one asset carry three different ETags. Responses that Nginx compresses on the fly get a weak ETag (W/"...") instead. Both behaviors are correct, but do not expect one ETag per URL when you compare responses.
To avoid this headache, verify three things:
- Make sure your CDN forwards the
Accept-Encodingheader to your origin without stripping Brotli or normalizing it to gzip-only. - Explicitly set
add_header Vary "Accept-Encoding" always;in Nginx so the edge stores separate cache entries forbr,gzip, and raw responses. - Check whether your CDN compresses responses itself. Many can apply Brotli at the edge, in which case the origin’s pre-compressed files mainly save origin CPU and origin-to-edge bandwidth.
Testing Origin Responses with cURL
Skip the browser when testing this. DevTools caches aggressively and makes it hard to tell what the origin actually sent. Run these on the server itself, so curl reaches Nginx directly and bypasses the CDN. Replace main.js with a file that exists in your build.
Test for Brotli support:
curl -I -H "Accept-Encoding: br" http://127.0.0.1/main.js -H "Host: assets.example.com"You should see response headers like these (your dates and server version will differ; the line that matters is Content-Encoding: br):
HTTP/1.1 200 OK
Server: nginx
Content-Type: application/javascript
Last-Modified: Sun, 16 Mar 2025 04:12:00 GMT
Vary: Accept-Encoding
Content-Encoding: br
Cache-Control: public, max-age=31536000, immutableNext, verify Gzip fallback for clients that don’t support Brotli:
curl -I -H "Accept-Encoding: gzip" http://127.0.0.1/main.js -H "Host: assets.example.com"You should get Content-Encoding: gzip back.
Finally, test with no encoding headers to confirm raw asset delivery:
curl -I http://127.0.0.1/main.js -H "Host: assets.example.com"This request should omit Content-Encoding completely and return the full Content-Length of your source file. If you get a 404 here, your build script deleted the uncompressed assets.
Handling Font Assets and Cross-Origin Rules
Web fonts like WOFF2 are already compressed using a variant of Brotli at the binary level. Pre-compressing a .woff2 file wastes build time and disk space for zero gain—and can even make the file slightly larger.
Exclude woff and woff2 from compression, but make sure your location block adds CORS headers if fonts live on a separate asset subdomain. Without them, browsers block font rendering during CSS parsing.
location ~* \.(?:woff|woff2|ttf)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
# Do not look for pre-compressed copies of font files
gzip_static off;
brotli_static off;
try_files $uri =404;
}If you run into CORS issues with fonts pulled through an edge tier, walk through our steps to fix CDN font CORS errors and edge cache rules.
Comparing Payload Sizes on Your Own Bundle
The gain depends on what is in your bundle, so measure it instead of trusting someone else’s benchmark. After a build, print the byte counts of one asset and its two compressed siblings:
wc -c dist/main.js dist/main.js.gz dist/main.js.brFor JavaScript and CSS, the level-11 .br file is normally the smallest of the three, clearly ahead of gzip -9, and both beat what dynamic compression produces at the lower levels a server can afford per request. Smaller files mean less egress and faster downloads on slow mobile connections.
If It Still Doesn’t Work
nginx -treportsunknown directive "brotli_static": the Brotli module isn’t loaded. Install the two packages above (or add theload_modulelines for a self-compiled module) and test again.- No
Content-Encodingheader even withAccept-Encoding: br: the.brfile is missing next to the original, the request doesn’t match thelocationblock, or you tested a file type the script didn’t compress. Check the folder withls. - The origin returns Brotli but the CDN serves gzip or nothing: the CDN strips or rewrites
Accept-Encodingon its way to the origin, or compresses on its own. Check its compression settings, as described in the Accept-Encoding section above. - A 404 for clients that send no
Accept-Encoding: the uncompressed originals were deleted. In the Vite plugin, setdeleteOriginalAssets: falseand rebuild; the shell script above always keeps the originals (-kand--keep).
Frequently Asked Questions
What happens if the .br file is missing from disk?
Nginx simply moves on to the next option. With brotli_static on;, a missing .br file means it tries gzip_static for a .gz file, then dynamic compression if brotli on; or gzip on; is set, and finally the raw file. Clients won’t get a 404 as long as the uncompressed file is present.
Should I compress HTML files ahead of time?
Only if your site is fully static (like Hugo, Astro, or a Next.js static export). For dynamic WordPress setups or SSR apps, you can’t pre-compress HTML because the markup renders on each request. Leave dynamic Gzip or Brotli at level 4 or 5 for dynamic text/html routes.
Why does my CDN return Gzip even when my browser supports Brotli?
This happens when the CDN doesn’t support Brotli upstream fetches or when an edge rule forces Gzip transcoding. Some CDN providers fetch Gzip from the origin to keep a single edge cache key, then transcode to Brotli on the fly. Check your edge provider’s compression and cache key settings.
Can I pre-compress files using Zopfli instead of standard gzip?
Yes. Zopfli produces 100% standard-compliant Gzip files that work everywhere while shaving off an extra 3% to 8% compared to gzip -9. It takes significantly longer to run, but in a build pipeline where you compress once and serve millions of times, it’s worth the extra CPU cycles.
Next Steps
Add the compression script (or the Vite plugin) to your regular build so every deploy ships fresh .br and .gz files, and repeat the three curl checks after the next release. With cheap cache misses in place, the next way to protect the origin is to have fewer of them at once; see how to prevent CDN cache stampedes with origin shield and request collapsing.

