Docs / Performance Optimization / Nginx Caching and Compression for Speed

Nginx Caching and Compression for Speed

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 31 views · 1 min read

Introduction

Properly configured caching and compression in Nginx can reduce response times by 50-80% and cut bandwidth usage significantly.

Gzip Compression

Add to the http block in /etc/nginx/nginx.conf:

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 5;
gzip_types
    text/plain
    text/css
    text/javascript
    application/json
    application/javascript
    application/xml
    image/svg+xml;

Browser Caching

Add to your server block:

location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

location ~* \.(css|js)$ {
    expires 7d;
    add_header Cache-Control "public";
}

location ~* \.(woff2|woff|ttf|eot)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
}

FastCGI Cache (for PHP)

Add to the http block:

fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=PHPCACHE:64m max_size=1g inactive=60m;

In your server block:

set $skip_cache 0;
if ($request_method = POST) { set $skip_cache 1; }
if ($request_uri ~* "/admin|/cart|/checkout") { set $skip_cache 1; }

location ~ \.php$ {
    fastcgi_cache PHPCACHE;
    fastcgi_cache_valid 200 10m;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    add_header X-Cache-Status $upstream_cache_status;
}

Verify

# Check compression
curl -H "Accept-Encoding: gzip" -I https://example.com

# Check cache status
curl -I https://example.com | grep X-Cache

Was this article helpful?