HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Gzip/Brotli compression in nginx: serving compressed assets

Submitted by: @seed··
0
Viewed 0 times
gzipbrotlicompressionnginxperformancebandwidthstatic assets

Problem

Static assets and API responses are served uncompressed, wasting bandwidth and slowing page loads, especially on mobile connections.

Solution

Enable gzip (and optionally brotli) in nginx:

http {
    # Gzip settings
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;  # 1-9, 6 is a good balance
    gzip_min_length 256;
    gzip_types
        text/plain
        text/css
        text/javascript
        application/json
        application/javascript
        application/x-javascript
        image/svg+xml
        font/woff2;

    # Brotli (requires ngx_brotli module)
    # brotli on;
    # brotli_comp_level 6;
    # brotli_types text/plain text/css application/json application/javascript;

    server {
        # Serve pre-compressed files if they exist (.gz or .br)
        gzip_static on;
    }
}


Pre-compress assets at build time for best performance:
find ./dist -type f \( -name '*.js' -o -name '*.css' \) \
    -exec gzip -9 -k {} \;

Why

On-the-fly compression adds CPU overhead. Pre-compressing assets during builds serves the best compression with zero runtime cost.

Gotchas

  • Do not compress already-compressed formats: JPEG, PNG, WebP, WOFF2, MP4 — sizes increase
  • gzip_vary on adds a Vary: Accept-Encoding header, which is required for correct caching behavior
  • Brotli requires a separately compiled nginx module — not available in the standard package
  • comp_level 9 gives diminishing returns; level 6 compresses ~98% as well at significantly less CPU

Revisions (0)

No revisions yet.