Nginx Config by Example: Compression
Reducing bandwidth usage with Gzip compression through this code example showing gzip enablement, compression level tuning, minimum file size threshold, MIME type specification, and Vary header configuration.
Code
http {
# Enable Gzip
gzip on;
# Compression level (1-9)
# 5 is a good balance between CPU usage and size
gzip_comp_level 5;
# Minimum file size to compress (bytes)
gzip_min_length 256;
# Compress even for proxied requests
gzip_proxied any;
# MIME types to compress
# text/html is compressed by default
gzip_types
text/plain
text/css
text/javascript
application/javascript
application/json
application/xml
image/svg+xml;
# Add 'Vary: Accept-Encoding' header
gzip_vary on;
}Explanation
Gzip compression reduces response body size before transmission, significantly decreasing bandwidth usage and improving page load times especially for text-based files like HTML, CSS, JavaScript, and JSON. Compression is particularly effective for text content which typically compresses to 60-80% smaller sizes. The gzip on directive enables the compression module, which operates transparently to clients that support compression via the Accept-Encoding: gzip request header.
The gzip_comp_level directive controls compression ratio versus CPU usage, ranging from 1 (fastest, least compression) to 9 (slowest, maximum compression). Levels 3-5 provide optimal balance for most scenarios, as higher levels provide diminishing returns while consuming significantly more CPU. The gzip_min_length directive prevents compressing very small files where compression overhead might actually increase size, with 256 bytes being a common threshold.
The gzip_types directive specifies MIME types eligible for compression, with text/html always compressed when gzip is enabled. Binary formats like images (JPEG, PNG) and videos should be excluded as they are already compressed and won't benefit. The gzip_vary on directive adds the Vary: Accept-Encoding header, instructing caching proxies to maintain separate cached versions for compressed and uncompressed responses. The gzip_proxied directive controls compression for proxied requests, with any enabling compression regardless of proxy headers.
Code Breakdown
gzip on enables compression module for supported clients.gzip_comp_level 5 balances compression ratio and CPU usage.gzip_types specifies MIME types, excludes pre-compressed binaries.gzip_vary on adds Vary header for proper proxy caching.
