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 longmax-ageplusimmutable. 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
- Open the Nginx Browser Caching Generator and choose the file types you serve.
- Set the cache duration for each group, longer for hashed assets, shorter for HTML.
- Copy the generated
locationblock into your server config. - Run
nginx -tto test the configuration for syntax errors. - Apply it with
nginx -s reloadso 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.
Related tools
- .htaccess Browser Caching Generator: same caching rules for Apache servers using mod_expires.
- Cache-Control Header Generator: build a standalone Cache-Control value for any server or CDN.
- .htaccess Gzip Compression Generator: pair caching with compression to shrink transfer sizes.
Match the cache duration to how often each file changes, test with nginx -t, reload, and let browsers do the rest.