Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 30 ยท HTTPS and Modern HTTP

HTTP/2, HTTP/3, gzip and Brotli

Enable HTTP/2 and HTTP/3 in nginx and Apache, understand multiplexing and what it makes obsolete, and tune gzip and Brotli compression: levels, types and what to skip.

Once HTTPS works, two cheap changes make pages load noticeably faster: a newer version of the HTTP protocol, and compression of text responses. Neither needs any change to your application, only a few lines of server configuration.

HTTP/1.1 handles one request at a time per connection, so browsers open about six connections per host and queue the rest. HTTP/2 sends many requests at once over a single connection. HTTP/3 does the same over QUIC, a protocol built on UDP, which avoids a whole family of slowdowns when packets are lost. Separately, compression shrinks HTML, CSS, JavaScript and JSON to a fraction of their size before they cross the network.

This lesson shows how to turn each feature on, what it changes about good practice, and which files should never be compressed. It assumes HTTPS is already configured as in HTTPS, TLS and Let's Encrypt.

Three upgrades, little work

HTTP/2 Many requests, one connection.
HTTP/3 QUIC over UDP, fewer stalls.
Compression Text shrinks by two thirds or more.
1 / 2

Enabling HTTP/2

In nginx 1.25.1 and newer, HTTP/2 is a separate switch in the server block:

NGINX
server {
    listen 443 ssl;
    http2 on;
    server_name example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

Older versions write it on the listen line instead: listen 443 ssl http2;. That form still works in new versions but is marked deprecated. Browsers speak HTTP/2 only over TLS, so the ssl part is required in practice; the negotiation happens inside the TLS handshake (a field called ALPN).

In Apache, enable mod_http2 and declare which protocols the site accepts:

APACHE
# a2enmod http2
<VirtualHost *:443>
    ServerName example.com
    Protocols h2 http/1.1
    # ... SSL settings ...
</VirtualHost>

Protocols h2 http/1.1 lists them in order of preference, and the second entry is the fallback for older clients. Apache's HTTP/2 works with the event or worker MPM. With the prefork MPM (which classic mod_php forces) it is not supported, one more reason to move PHP to FPM, as covered in PHP, FastCGI and Application Servers.

Check what you got with curl -sI --http2 https://example.com | head -1. The first line should start with HTTP/2 200.

What multiplexing changes

With HTTP/1.1, the cost of a request was the main enemy, so a whole set of tricks appeared: bundling all scripts into one file, sprite sheets that join many images into one, and domain sharding, which spreads assets over several host names to get more connections. HTTP/2 makes most of these unnecessary and some harmful:

  • Bundling still helps compression and reduces per-file overhead, but extreme bundles hurt caching: changing one line invalidates one big file. Moderately sized, separately cached files are fine now.
  • Domain sharding is counterproductive. Each extra host needs its own DNS lookup, TCP and TLS connection, and splits the single well-used connection into several poor ones.
  • Header compression (HPACK) makes repeated cookies and long headers cheap, so request overhead drops further.

The old HTTP/2 "server push" feature is deprecated in browsers; use <link rel="preload"> or 103 Early Hints instead.

HTTP/2 does not make slow code fast: one slow backend response is still slow, and a single lost packet can still stall every stream on that connection, because all streams share one TCP connection. That is the weakness HTTP/3 removes.

Try the effect with arithmetic. This stand-in models 24 requests of various durations. HTTP/1.1 has six connections that each handle one request at a time; HTTP/2 shares one connection and runs requests concurrently, with a small extra cost for each request. The numbers are invented for the demo, and the model ignores bandwidth limits, so it shows the shape of the benefit rather than a benchmark.

JS Six connections versus one multiplexed connection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the sharded variant ends up slower than plain HTTP/1.1 once the extra connection setup is counted, while a single HTTP/2 connection beats both. In real networks the gap also depends on bandwidth and on how many requests actually run in parallel.

Enabling HTTP/3

HTTP/3 runs over QUIC on UDP port 443. nginx supports it from version 1.25, if it was built with the QUIC module (official packages and many distributions include it; check nginx -V for --with-http_v3_module).

NGINX
server {
    listen 443 ssl;
    listen 443 quic reuseport;     # UDP, the QUIC listener
    http2 on;
    http3 on;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;     # QUIC requires TLS 1.3

    add_header Alt-Svc 'h3=":443"; ma=86400' always;
}

Browsers do not try HTTP/3 first. They connect over HTTP/2, see the Alt-Svc header ("this site is also available over h3 on port 443"), and switch on later visits. So you must also open UDP 443 in your firewall and your cloud provider's security group; forgetting this is the usual reason HTTP/3 "does nothing". Clients silently fall back to HTTP/2 when UDP is blocked, which makes the mistake harmless but easy to miss. Check with curl --http3 -I https://example.com (needs a curl build with HTTP/3 support).

Apache's standard releases do not include HTTP/3. If you need it for an Apache site, put nginx, a CDN or another HTTP/3-capable proxy in front, exactly the layout from Nginx in Front of Apache.

Compression with gzip

The nginx gzip module is part of the standard build but off by default:

NGINX
http {
    gzip on;
    gzip_comp_level 5;
    gzip_min_length 256;
    gzip_vary on;
    gzip_proxied any;
    gzip_types text/css application/javascript application/json
               image/svg+xml application/xml text/plain;
}
  • text/html is always compressed once gzip on is set, so it is not listed in gzip_types.
  • gzip_comp_level runs from 1 (fast) to 9 (smallest). Levels above 5 or 6 cost much more CPU for tiny extra savings, so 4 to 6 is the sweet spot for responses created on the fly.
  • gzip_min_length skips tiny responses, where the gzip header outweighs the gain.
  • gzip_vary on adds Vary: Accept-Encoding, so caches keep a compressed and an uncompressed copy apart.
  • gzip_proxied any allows compression of responses to requests that came through proxies, which is needed when a CDN or a proxy sits in front.

In Apache, mod_deflate does the same job:

APACHE
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml
    DeflateCompressionLevel 5
</IfModule>

Brotli

Brotli compresses text better than gzip at comparable speed settings, typically ten to twenty percent smaller for HTML, CSS and JavaScript, and every modern browser supports it (browsers request it only over HTTPS, advertising Accept-Encoding: br). Apache has mod_brotli, available from 2.4.26. nginx does not include Brotli in its standard build: it comes from the third-party ngx_brotli module, which many distributions package as an extra. Where it is installed:

NGINX
brotli on;
brotli_comp_level 5;
brotli_types text/css application/javascript application/json image/svg+xml;

Brotli's highest levels (up to 11) are slow, which makes them right for pre-compression at build time and wrong for compressing on the fly. A common recipe: compress static assets once with Brotli level 11 and gzip level 9 during the build, then let the server hand out the ready-made .br or .gz file (nginx gzip_static on;, or brotli_static on;, covered in Static Files, Caching and MIME Types).

The following stand-in uses Node's built-in zlib, which includes both algorithms, to compress some repetitive text at different levels. Sizes depend on the input and the zlib version, so treat them as an illustration.

Node.js gzip versus Brotli on sample text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the diminishing returns (gzip level 1 to 5 saves about a sixth of the remaining size, level 5 to 9 about a tenth), how Brotli ends up clearly smaller than gzip on this text, and how data without patterns (a stand-in for JPEGs, videos and archives) does not shrink at all: the 4000 random-like bytes grow to 4023, and gzipping the gzip output also grows it. That is the argument for compressing text types only.

What not to compress

  • Already-compressed formats: JPEG, PNG, WebP, AVIF, GIF, MP4, WebM, MP3, ZIP, GZ, WOFF2. Compression only burns CPU. SVG, on the other hand, is text and compresses well.
  • Tiny responses, below a few hundred bytes.
  • Streaming responses such as text/event-stream, where compression buffers data (WebSockets, Streaming and Long Requests).
  • Secrets mixed with attacker-controlled text. The BREACH attack can recover secrets (such as a CSRF token) from compressed HTTPS responses that reflect user input. Frameworks defend against it with per-response token masking; if you serve pages that mix both, keep that in mind.
  • Anything compressed twice by a proxy and a backend, as covered in the previous lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change in good practice does HTTP/2 encourage?

    Sharding was a workaround for the limit of connections per host. With HTTP/2 each extra host only adds setup cost.
  2. 2. HTTP/3 is configured in nginx but browsers never use it. What is the most likely cause?

    HTTP/3 uses QUIC over UDP. If UDP 443 is blocked, clients fall back to HTTP/2 without any error.
  3. 3. Why are image files like JPEG and WebP left out of gzip_types?

    Compressing data that has no remaining patterns barely changes its size. SVG is the exception because it is text.
  4. 4. Where is Brotli level 11 appropriate?

    The top quality levels are slow. Pay that cost once at build time, then serve the ready-made .br file.

Summary

  • Enable HTTP/2 with http2 on; (nginx) or Protocols h2 http/1.1 (Apache, event or worker MPM), and drop bundling extremes and domain sharding.
  • HTTP/3 needs nginx 1.25+ with QUIC, listen 443 quic, an Alt-Svc header and open UDP port 443; stock Apache has no HTTP/3.
  • Use gzip level 4 to 6 for dynamic text, Brotli where available, and pre-compress static assets at high levels.
  • Compress only text types; skip images, video, archives, fonts that are already packed, tiny responses and event streams.
  • Compress in one place only, and keep BREACH in mind for secrets reflected next to user input.

Next: control who may use the server in Access Control and Rate Limiting.