Nginx Gzip Compression Configuration

Enable and configure gzip compression in Nginx to reduce HTTP response sizes by up to 70 percent. Covers MIME types, compression levels, and best tips.

Performance

Detailed Explanation

Gzip compression reduces the size of HTTP responses before they are sent to the client, resulting in faster page loads and significantly lower bandwidth consumption for text-based content.

Basic Gzip Configuration

Enable gzip in the http block and specify which MIME types to compress. Text-based formats like HTML, CSS, JavaScript, and JSON benefit most from compression because they contain highly repetitive patterns.

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

Compression Level

The gzip_comp_level ranges from 1 (fastest, least compression) to 9 (slowest, most compression). Level 5 provides an excellent balance between CPU usage and compression ratio for most workloads. Going above level 6 yields diminishing returns in file size reduction while consuming significantly more CPU cycles per request.

The gzip_vary Directive

Setting gzip_vary on adds a Vary: Accept-Encoding response header, which tells caching proxies and CDNs to store both compressed and uncompressed versions of the response. This prevents the edge case of serving gzipped content to clients that cannot handle decompression.

Minimum Length

The gzip_min_length directive skips compression for responses smaller than the specified size in bytes. Very small responses gain little from compression, and the gzip overhead (headers and checksum) can actually make them larger. A threshold of 256 bytes works well for most applications.

Static Gzip Files

For maximum performance, pre-compress your static files during your build process and use gzip_static on. Nginx will automatically serve the pre-compressed .gz file if it exists alongside the original, completely avoiding runtime compression overhead.

location /static/ {
    gzip_static on;
    expires max;
}

What Not to Compress

Avoid compressing already-compressed binary formats like JPEG, PNG, GIF, WOFF, and ZIP files. Attempting to compress these wastes CPU cycles with no meaningful size reduction and can occasionally produce slightly larger outputs.

Verifying Compression

Test your configuration with curl -H "Accept-Encoding: gzip" -I https://example.com and check for the Content-Encoding: gzip header in the response to confirm compression is active.

Use Case

You want to improve your website's page load speed and reduce bandwidth costs by compressing text-based assets like HTML, CSS, and JavaScript before they are sent to visitors.

Try It — Nginx Config Generator

Open full tool