How to Enable Gzip & Brotli Compression in Nginx for High PageSpeed
Text-based web assets contain repetitive tokens that compress dramatically. Enabling Nginx compression reduces transfer bandwidth, accelerates First Contentful Paint (FCP), and improves Core Web Vitals.
Interactive Nginx Config Generator
# Place in http {} block or server {} block
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 256;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types
application/atom+xml
application/geo+json
application/javascript
application/x-javascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/xhtml+xml
application/xml
font/eot
font/otf
font/ttf
image/svg+xml
text/css
text/javascript
text/plain
text/xml;
# If ngx_brotli module is installed:
# brotli on;
# brotli_comp_level 6;
# brotli_types text/plain text/css application/javascript application/json image/svg+xml;Directives & Architecture Explained
gzip on;Enables dynamic Gzip compression of server HTTP responses.
gzip_comp_level 6;Optimal trade-off between CPU consumption and compression ratio (levels 7-9 yield negligible gains with high CPU overhead).
gzip_min_length 256;Skips compression for files smaller than 256 bytes, where compression headers would actually increase total payload size.
gzip_vary on;Adds "Vary: Accept-Encoding" header so intermediate CDNs cache compressed and uncompressed assets separately.
Production Verification & Reload Workflow
sudo nginx -tTest syntax of gzip configuration
curl -H "Accept-Encoding: gzip" -I http://example.com/main.jsVerify Content-Encoding: gzip header is returned in response
Production Troubleshooting Tips
- β’Do NOT compress already compressed binary formats like PNG, JPEG, WebP, MP4, or ZIP β it wastes server CPU and can enlarge the file.
- β’Ensure gzip_vary on is enabled so corporate proxy caches do not serve Gzipped content to ancient legacy clients.
- β’If testing locally with curl without -H "Accept-Encoding: gzip", Nginx will correctly return uncompressed plain text.
Frequently Asked Questions
Why level 6 instead of level 9?
Level 6 achieves 95% of maximum compression with minimal CPU latency. Levels 7-9 require up to 4x more CPU cycles for less than 1% file size reduction.
Is Brotli better than Gzip?
Yes! Brotli compresses text files 14-25% smaller than Gzip at similar compression speeds and is supported by all modern browsers.