How to Set Nginx Cache-Control Headers for Static Assets

How to Set Nginx Cache-Control Headers for Static Assets

Setting up Nginx cache headers tells browsers to keep your CSS, JS, and images locally instead of re-downloading them on every visit. Done right, repeat visits load almost instantly and your server handles fewer requests. Here is how Cache-Control in Nginx works and how to generate a config block in seconds.

Why browser caching matters

Every uncached asset is another round trip. When a browser already holds a fresh copy of your stylesheet or logo, it skips the network entirely. The two directives that control this are expires (which sets the Expires and max-age values) and Cache-Control (which adds finer rules like immutable or public). You want long caching for assets that rarely change and short caching for files that update often.

The location block pattern

Caching in Nginx lives inside a location block that matches file extensions. A typical setup looks like this:

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

The regex matches static asset extensions, expires 1y sets a one-year max-age, and add_header Cache-Control layers on the extra directives. For HTML, use a much shorter window so content updates reach visitors quickly.

Long max-age vs short max-age

The right value depends on whether the filename changes when the content does.

  • Hashed or fingerprinted assets (like app.4f3a2b.css): use a long max-age plus immutable. The hash changes when the file changes, so a year is safe.
  • HTML pages: use a short max-age, often a few minutes or no-cache, so edits and new posts show up right away.
  • Fonts and images without hashes: a moderate value such as 30 days is a reasonable middle ground.

Rather than memorizing the syntax, the Nginx Browser Caching Generator builds the full block for you with sensible per-file-type defaults.

Generate and apply your config

  1. Open the Nginx Browser Caching Generator and choose the file types you serve.
  2. Set the cache duration for each group, longer for hashed assets, shorter for HTML.
  3. Copy the generated location block into your server config.
  4. Run nginx -t to test the configuration for syntax errors.
  5. Apply it with nginx -s reload so the changes take effect with no downtime.

The generator runs fully in your browser, so nothing about your server or config ever leaves your device.

Match the cache duration to how often each file changes, test with nginx -t, reload, and let browsers do the rest.

← All posts