Lesson 17 / 25

Compression

Compress responses with gzip and serve pre-compressed files.

Fewer bytes over the wire

Text responses (HTML, CSS, JavaScript, JSON, SVG) compress very well, often to a fraction of their size, which speeds up page loads, especially on mobile networks. Enable gzip on; and list compressible gzip_types (text/html is always included); skip already-compressed formats such as JPEG, PNG, WebP and video, which only waste CPU. gzip_comp_level trades CPU for size (levels around 4 to 6 are a good balance), gzip_min_length skips tiny responses, and gzip_vary on; adds Vary: Accept-Encoding so caches store compressed and uncompressed variants separately. gzip_proxied any; also compresses proxied responses. For static assets, compress at build time and enable gzip_static on; so NGINX serves app.js.gz directly without compressing on every request. Brotli usually compresses text better than gzip; it is available through the third-party ngx_brotli module or prebuilt packages, with brotli_static for pre-compressed .br files.

Gzip for dynamic and static content

Compress text types, skip images, serve pre-built .gz files.

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

    server {
        location /assets/ {
            gzip_static on;          # serve app.3f9a.js.gz if present and accepted
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
}

Vacuum-packing clothes for a trip

Compression is vacuum-packing: text squeezes down enormously, while already-dense items such as images do not shrink, so packing them just wastes effort.

Quick check: Which content type should normally NOT be gzip-compressed by NGINX?

  • application/json
  • image/jpeg
  • text/css
  • application/javascript
Answer

image/jpeg — JPEG is already compressed; gzipping it wastes CPU for no benefit.