Basic Gzip Configuration
http {
# Enable gzip
gzip on;
# Compression level (1-9, higher = more compression)
gzip_comp_level 5;
# Minimum size to compress
gzip_min_length 256;
# Compress for proxied requests
gzip_proxied any;
# Vary header for caching
gzip_vary on;
# MIME types to compress
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
application/x-javascript
image/svg+xml;
}Optimized Configuration
# /etc/nginx/snippets/gzip.conf
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
# Disable for old browsers
gzip_disable "msie6";
# Buffer size
gzip_buffers 16 8k;
# HTTP version
gzip_http_version 1.1;
# Comprehensive MIME types
gzip_types
application/atom+xml
application/geo+json
application/javascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/vnd.ms-fontobject
application/wasm
application/x-javascript
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
font/eot
font/otf
font/ttf
image/bmp
image/svg+xml
text/cache-manifest
text/calendar
text/css
text/javascript
text/markdown
text/plain
text/vcard
text/vnd.rim.location.xloc
text/vtt
text/x-component
text/x-cross-domain-policy
text/xml;Use in Server
server {
listen 443 ssl http2;
server_name example.com;
include snippets/gzip.conf;
# ... rest of config
}Disable for Specific Locations
# Don't compress already compressed files
location ~* \.(gz|zip|rar|7z)$ {
gzip off;
}
# Don't compress images (already compressed)
location ~* \.(jpg|jpeg|png|gif|webp)$ {
gzip off;
}Pre-compressed Files
# Serve pre-compressed .gz files
gzip_static on;
# Files must exist: style.css and style.css.gz
location ~* \.(css|js)$ {
gzip_static on;
expires 30d;
}# Create pre-compressed files
gzip -k -9 /var/www/html/css/style.css
gzip -k -9 /var/www/html/js/app.jsTesting Compression
# Check if gzip is working
curl -H "Accept-Encoding: gzip" -I https://example.com/style.css
# Should show: Content-Encoding: gzip
# Compare sizes
curl -so /dev/null -w '%{size_download}' https://example.com/style.css
curl -sH "Accept-Encoding: gzip" -o /dev/null -w '%{size_download}' https://example.com/style.cssCompression Levels
| Level | Speed | Compression |
|---|---|---|
| 1 | Fastest | Lowest |
| 5 | Balanced | Good (recommended) |
| 9 | Slowest | Highest |
For most cases, level 5 provides the best balance of CPU usage and compression ratio.
- nginx
- gzip
- compression
- performance
- bandwidth