HTTP, TLS & Web Performance

Compression With Gzip and Brotli

See how HTTP compression works, which files to compress, how to turn on gzip and Brotli, and how to confirm it is working.

Key takeaways

  • The browser lists the encodings it understands in Accept-Encoding, and the server names the one it used in Content-Encoding.
  • Brotli usually produces smaller text files than gzip, while gzip remains the fallback almost every client understands.
  • Pre-compress static files at high settings during your build, and use moderate settings for pages generated on the fly.
  • Responses that vary by encoding need Vary: Accept-Encoding so caches don't serve the wrong version.
  • Already compressed formats gain almost nothing and waste processor time.

HTTP compression shrinks text files on the server and has the browser expand them again, so fewer bytes cross the network. Turn on both gzip and Brotli for HTML, CSS, JavaScript, JSON, SVG and similar text formats. Skip files that are already compressed, such as JPEG, WebP, MP4 and ZIP.

It's one of the cheapest speed improvements available. Often it's already partly switched on, so the first job is to check.

How the negotiation works

When your browser requests a page, it sends a header such as:

Accept-Encoding: gzip, deflate, br, zstd

The server picks one it supports and labels the response:

Content-Encoding: br
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding

Content-Type still describes the underlying file. Content-Encoding describes the wrapper that has to be removed first. If a client sends no suitable value, the server should send the plain version. For background on headers in general, see HTTP requests, responses and headers.

Negotiating a compressed response
Browser Web server GET /app.js, accepts br and gzip 1 200 OK, Content-Encoding: br 2 The browser decompresses it Later requests reuse the cached copy 3 Or revalidate it Browser Web server GET /app.js, accepts br and gzip 1 200 OK, Content-Encoding: br 2 The browser decompresses it Later requests reuse the cached copy 3 Or revalidate it

What the algorithms do

Both gzip and Brotli are lossless: the browser recovers exactly the original bytes. Both rely on two ideas. First, replace a repeated sequence with a short reference back to where it appeared before. Second, give frequent symbols shorter codes than rare ones.

Gzip is a file format (RFC 1952) around the DEFLATE method (RFC 1951). It's old, fast and supported nearly everywhere.

Brotli (RFC 7932) was developed at Google. It can look back across a larger window, models context more carefully and ships with a built-in dictionary of strings common in web content. That dictionary helps especially with small files. Browsers advertise Brotli support on HTTPS connections.

Zstandard, sent as zstd, is a newer option known for speed. Support in browsers and servers has been growing; check your own stack before depending on it. There is also work on shared compression dictionaries, where a previous version of a file helps compress the next one. Treat that as an advanced option and confirm support.

Why text shrinks so well

Markup and code are repetitive. A product listing repeats the same tags and class names for every item. A JSON response repeats the same field names in every record. Each repeat can be replaced by a pointer a few bytes long, so large, regular files often compress to a small fraction of their size.

Content that looks random doesn't compress. Encrypted data, and files that have already been squeezed, have no patterns left to exploit. This is also why order matters in a delivery chain: data must be compressed before it's encrypted. HTTPS handles encryption underneath HTTP, so content encoding happens first without any extra work from you.

Compression differs from the header compression in HTTP/2 and HTTP/3, which have their own schemes for request and response headers. Content encoding applies only to the body. The protocol differences are explained in HTTP/1.1 vs. HTTP/2 vs. HTTP/3.

Which files to compress

Compress Leave alone
HTML, CSS, JavaScript JPEG, PNG, WebP, AVIF
JSON, XML, feeds MP4, WebM, MP3
SVG WOFF and WOFF2 fonts
Plain text, source maps ZIP, gzip and similar archives

Older font formats such as TTF and OTF do benefit, but converting them to WOFF2, which uses Brotli internally, is better. Image savings come from format and dimension choices instead, covered in image formats for speed.

Very small responses are a special case. Wrapping a few hundred bytes adds header overhead and can even make the result bigger, so servers usually offer a minimum size setting.

Levels: size against processor time

Gzip offers levels from 1 to 9, and Brotli quality runs from 0 to 11. Higher levels search harder for repetition. The gains shrink as you go up, while the time cost climbs, steeply so at the top of Brotli's range.

That leads to a simple rule:

  • Static files change only when you deploy. Compress once at maximum, save the result next to the original, and serve it.
  • Dynamic responses are compressed on each request. Use a middle level so compression doesn't delay the first byte.
Two ways to apply compression
Pre-compressed Done once during build or deploy Highest levels are affordable No per-request processor cost Files must be rebuilt when sources change On the fly Done as each response is sent Moderate levels keep latency low Works for generated pages and APIs Uses server processor time under load VS Pre-compressed Done once during build or deploy Highest levels are affordable No per-request processor cost Files must be rebuilt when sources change On the fly Done as each response is sent Moderate levels keep latency low Works for generated pages and APIs Uses server processor time under load

Turning it on

Hosts and content delivery networks often compress automatically or offer a single switch. If you manage the server yourself, here are starting points.

For nginx, gzip is built in:

gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_vary on;
gzip_proxied any;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_static on;

text/html is always included and doesn't need listing. gzip_static serves a ready-made .gz file when one sits beside the original; it depends on a module that some builds leave out. Brotli in open source nginx comes from a separate module, which adds directives such as brotli on; and brotli_static on;.

For Apache, enable mod_deflate and, where available, mod_brotli:

AddOutputFilterByType BROTLI_COMPRESS text/html text/css application/javascript application/json image/svg+xml
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml

How the two filters interact depends on configuration order, so test the responses after changing it.

To create compressed copies during a build on Linux or macOS:

gzip -9 -k app.js
brotli -q 11 -k app.js

The -k flag keeps the original file. You need the brotli command-line tool installed.

Where compression should happen

Many sites have several layers: an application, a reverse proxy in front of it, and perhaps a content network in front of that. Any of them can compress. Pick one deliberately.

Compressing at the proxy keeps application code simple and puts all the rules in one place. Compressing at the edge network offloads your servers, but you should still compress between your origin and the edge if you pay for that traffic or the link is slow. Check how your provider handles an already encoded response: some pass it through, some decompress and re-encode it, and some only compress certain content types or sizes.

A build step is the natural home for static files. Add it to your deployment script so that a changed source file can never sit beside a stale compressed copy. Clearing old output before each build prevents the confusing case where the server keeps sending yesterday's code to every client that accepts Brotli while others see today's.

Checking that it works

Request a file while advertising support, discard the body and print the headers:

curl -s -D - -o /dev/null -H "Accept-Encoding: br, gzip" https://example.com/app.js

In Windows PowerShell, call curl.exe and use NUL in place of /dev/null. Look for Content-Encoding. To compare sizes, print the number of bytes downloaded:

curl -s -o /dev/null -w "%{size_download}\n" https://example.com/app.js
curl -s -o /dev/null -w "%{size_download}\n" -H "Accept-Encoding: br" https://example.com/app.js

In browser developer tools, the Network panel can show both the transferred size and the uncompressed size. More command recipes are in using curl to understand web requests.

Example: one text file sent three ways
Uncompressed 300KB Gzip 85KB Brotli, high quality 70KB Uncompressed 300KB Gzip 85KB Brotli, high quality 70KB

Real ratios depend heavily on the content. Hypothetical example: the numbers are made up to show the method, not a quote or an average.

Caches, security and other pitfalls

Caching. A shared cache may store a Brotli response and then receive a request from a client that only reads gzip. Vary: Accept-Encoding tells it to keep versions separate. Some CDNs handle this by normalizing the header themselves. Entity tags should also differ between encoded variants, a detail explained in ETags and conditional requests.

Double compression. If an application compresses output and a proxy compresses it again without updating headers, the browser shows garbage. Decide which layer is responsible.

Mislabelled files. A pre-compressed file served without Content-Encoding looks like binary noise. One served with the header but not actually compressed produces a decoding error.

Secrets in compressed responses. Attacks in the BREACH family exploit the fact that compressed size changes when attacker-supplied text matches a secret in the same response. The defenses include keeping secrets out of responses that echo user input, masking tokens so they differ on every response, using cross-site request protections such as SameSite cookies, and disabling compression for the specific sensitive responses. Static assets with no secrets aren't affected.

Streaming. Compression layers can buffer output while waiting for more data. If server-sent events or progressive responses arrive in bursts, check buffering and compression settings on every layer.

Requests can be compressed too

Compression is mostly discussed for responses, but a client can also send a compressed body with a Content-Encoding header, which is useful for bulk uploads between services. There's no automatic negotiation before the first request, so only do this when you know the server accepts it. A server that does should limit the expanded size, since a tiny upload can be crafted to decompress into an enormous amount of data and exhaust memory.

API responses deserve a check of their own. Teams often compress web pages and forget the JSON endpoints, which are among the most compressible content a site serves. Confirm that the content type your API uses, including any custom variant, appears in the server's list of types to compress.

What compression doesn't fix

A compressed JavaScript file still has to be decompressed, parsed and run at its full size. If a page feels sluggish after loading, remove code instead of squeezing it harder. Minification, which strips comments and whitespace, complements compression and slightly reduces parsing work.

Compression also does nothing for a slow database query or a distant server. Pair it with long browser caching for static files so repeat visitors download nothing at all, and keep an eye on the other causes of slow pages.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic