0
0
NginxHow-ToBeginner · 3 min read

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 - Adds Vary: Accept-Encoding header 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 the http block.
  • Not specifying gzip_types, which defaults to only text/html and misses other compressible types.
  • Setting gzip_comp_level too 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

DirectiveDescriptionDefault
gzipEnable or disable gzip compressionoff
gzip_typesList of MIME types to compresstext/html
gzip_min_lengthMinimum response size in bytes to compress20
gzip_comp_levelCompression level (1-9)1
gzip_varyAdd Vary header for proxiesoff

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.