How to Configure gzip Compression in nginx for Faster Web Performance
To configure
gzip compression in nginx, enable it with gzip on; and specify compression settings like gzip_types for content types. Add these directives inside the http block in your nginx configuration file and reload nginx to apply.Syntax
The main directives to enable and control gzip compression in nginx are:
gzip on;- Enables gzip compression.gzip_types- Specifies MIME types to compress (e.g., text/html, application/json).gzip_min_length- Minimum response size to compress.gzip_comp_level- Compression level from 1 (fastest) to 9 (best compression).gzip_vary- AddsVary: Accept-Encodingheader for proxies.
nginx
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
gzip_comp_level 5;
gzip_vary on;
}Example
This example shows a complete nginx http block enabling gzip compression for common text-based content types with moderate compression level.
nginx
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
gzip_comp_level 5;
gzip_vary on;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}Output
nginx configuration loaded successfully and gzip compression enabled for matching content types.
Common Pitfalls
Common mistakes when configuring gzip in nginx include:
- Forgetting to enable
gzip on;inside thehttpblock. - Not specifying
gzip_types, which defaults to onlytext/htmland misses other compressible types. - Setting
gzip_comp_leveltoo high (like 9) causing high CPU usage. - Not using
gzip_vary on;, which can cause caching issues with proxies. - Trying to compress already compressed files like images or videos (should be excluded).
nginx
http {
# Wrong: gzip not enabled
# gzip_types text/plain text/css;
# Right:
gzip on;
gzip_types text/plain text/css;
}Quick Reference
| Directive | Description | Default |
|---|---|---|
| gzip | Enable or disable gzip compression | off |
| gzip_types | List of MIME types to compress | text/html |
| gzip_min_length | Minimum response size in bytes to compress | 20 |
| gzip_comp_level | Compression level (1-9) | 1 |
| gzip_vary | Add Vary header for proxies | off |
Key Takeaways
Always enable gzip with
gzip on; inside the http block.Specify
gzip_types to cover all text-based content you want compressed.Use a moderate
gzip_comp_level (like 5) to balance CPU and compression.Enable
gzip_vary on; to avoid caching issues with proxies.Avoid compressing already compressed files like images or videos.