Slow load times are often caused by static files loading every time a visitor returns. With Nginx caching, images, CSS, and JavaScript are stored in the visitor's browser, so subsequent visits are much faster.

Browser Caching Setup

Add this to your Nginx site configuration:

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

This tells browsers to cache static files for 30 days. On repeat visits, the files load locally instead of being re‑downloaded.

Enable Gzip Compression

Compress files before sending them to browsers. This reduces transfer size and speeds up load times.

gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript application/json application/javascript;

With compression enabled, file sizes can shrink by 50% or more.

FastCGI Cache for Dynamic Sites

For WordPress or other dynamic sites, caching PHP responses can also help. Create a cache directory and configure it:

fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=fastcgicache:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";

How to Verify Cache is Working

Open browser developer tools (F12) → Network tab. Reload your page. Check the response headers for static files – you should see Cache-Control: max-age=2592000.

Clearing Cache When You Update Content

After updating a CSS or JS file, users may still see the old version. Solutions:

  • Rename the file (style.css → style.v2.css)
  • Add a query parameter (style.css?ver=2.0)
  • Clear Nginx cache manually: sudo rm -rf /var/cache/nginx/*

After setup, test your site with Google PageSpeed Insights or GTmetrix – you should see noticeable improvement.