Last updated

Web Performance

Enable GZIP compression in NGINX or Apache to reduce page load times and bandwidth.

Contents

  1. Enable GZIP in NGINX
  2. Enable GZIP in Apache
  3. Verify Compression
  4. Bonus: Enable Brotli (NGINX)

Enable GZIP in NGINX

Edit the main NGINX config or your server block:

sudo nano /etc/nginx/nginx.conf

Add or uncomment in the http block:

http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_types
        text/plain
        text/css
        text/javascript
        application/javascript
        application/json
        application/xml
        image/svg+xml
        font/woff
        font/woff2;
}
sudo nginx -t && sudo systemctl reload nginx

Enable GZIP in Apache

sudo a2enmod deflate
sudo nano /etc/apache2/mods-enabled/deflate.conf

    AddOutputFilterByType DEFLATE text/html text/plain text/css
    AddOutputFilterByType DEFLATE application/javascript application/json
    AddOutputFilterByType DEFLATE image/svg+xml font/woff font/woff2
sudo systemctl restart apache2

Verify Compression

# Check if gzip is enabled for a URL
curl -H "Accept-Encoding: gzip" -I https://example.com | grep -i content-encoding

# Expected output:
# content-encoding: gzip

Bonus: Enable Brotli (NGINX)

Brotli achieves better compression ratios than GZIP for text files.

sudo apt install -y libnginx-mod-http-brotli-static libnginx-mod-http-brotli-filter

# Add to nginx.conf http block:
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;