0
0
NginxHow-ToBeginner · 3 min read

How to Enable gzip Compression in Nginx for Faster Websites

To enable gzip in Nginx, add the gzip on; directive inside the http block of your Nginx configuration file. You can also configure options like gzip_types to specify which file types to compress and then reload Nginx to apply the changes.
📐

Syntax

The basic syntax to enable gzip in Nginx is to place gzip on; inside the http block. You can also add optional directives to control compression behavior:

  • gzip_types: Specifies MIME types to compress.
  • gzip_min_length: Minimum file size to compress.
  • gzip_comp_level: Compression level from 1 (fastest) to 9 (best compression).
  • gzip_disable: Disable gzip for specific user agents.
nginx
http {
    gzip on;
    gzip_types text/plain application/json application/javascript text/css;
    gzip_min_length 256;
    gzip_comp_level 5;
    gzip_disable "msie6";
}
💻

Example

This example shows a complete http block enabling gzip compression for common text-based file types. It sets a reasonable compression level and disables gzip for old Internet Explorer 6 browsers.

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_disable "msie6";

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html;
        }
    }
}
Output
Nginx starts successfully with gzip enabled; responses for specified MIME types are compressed when served.
⚠️

Common Pitfalls

Common mistakes when enabling gzip in Nginx include:

  • Placing gzip on; outside the http block, which will not enable gzip.
  • Not specifying gzip_types, which defaults to only compressing text/html.
  • Setting gzip_comp_level too high (like 9), which can increase CPU usage and slow down the server.
  • Forgetting to reload Nginx after changes, so gzip does not activate.

Example of wrong and right placement:

nginx
# Wrong placement (won't enable gzip)
gzip on;

# Correct placement inside http block
http {
    gzip on;
}
📊

Quick Reference

Here is a quick summary of key gzip directives in Nginx:

DirectiveDescriptionDefault
gzipEnables or disables gzip compressionoff
gzip_typesMIME types to compresstext/html
gzip_min_lengthMinimum file size to compress (bytes)20
gzip_comp_levelCompression level (1-9)1
gzip_disableDisable gzip for specified user agentsnone

Key Takeaways

Enable gzip by adding 'gzip on;' inside the 'http' block in nginx.conf.
Specify 'gzip_types' to compress common text-based file types beyond HTML.
Set 'gzip_comp_level' between 1 and 5 for good compression without high CPU load.
Always reload Nginx after configuration changes to apply gzip settings.
Avoid enabling gzip for very small files or incompatible browsers.