Without explicit caching headers, browsers and CDNs keep asking your origin whether static files have changed. This guide shows how to set immutable Cache-Control in Nginx for content-hashed assets, public, max-age=31536000, immutable, while your HTML always revalidates, so every deploy still reaches users straight away.
Quick answer: Give every built asset a content hash in its filename, serve files that match that pattern with Cache-Control: public, max-age=31536000, immutable, and serve index.html with Cache-Control: no-cache. A new deploy then changes only the HTML and the hashed names it points to.
- Configure your build tool (Vite, Webpack, esbuild) to put a content hash in each filename.
- Add an Nginx
locationthat matches hashed files and sends the one-year immutable header. - Send
no-cacheon HTML entry points. - Repeat any shared
add_headerlines inside each location block. - Reload Nginx and check the headers with
curl -Iat the origin and at the CDN.
In this guide
- Before You Start
- The Real Cost of 304 Not Modified Revalidations
- Why Query String Cache Busting Fails on CDNs
- Step 1: Put a Content Hash in Every Built Filename
- Step 2: Split Hashed Assets and HTML in Nginx
- Step 3: Avoid the add_header Inheritance Trap
- Step 4: Tune CDN Rules and Prevent 404 Cascades
- Step 5: Test and Verify the Headers with cURL
- Common Problems and Fixes
- Frequently Asked Questions
- Next Steps

Before You Start
- SSH access with
sudoto the server running Nginx, and your site’s server block file. - A front-end build you can rebuild, such as a Vite, Webpack or esbuild project.
- Access to your CDN’s cache settings, if a CDN sits in front of the server.
- About 30 minutes. Back up the server block first (
sudo cpit next to the original): a one-year header sent on the wrong file is hard to take back, because browsers keep the cached copy.
The Real Cost of 304 Not Modified Revalidations
When a stylesheet or JavaScript bundle is served without a long max-age, the browser keeps revalidating it with conditional requests carrying If-None-Match (ETag) or If-Modified-Since headers. Even when Nginx answers quickly with a 304 Not Modified, the browser still has to wait for that round trip before it can parse and run the asset.
On a page with dozens of static assets across fonts, scripts, and CSS, those round-trips add up on high-latency mobile networks, and every revalidation the CDN cannot answer on its own lands on your origin.
The MDN documentation on Cache-Control explains that the immutable directive tells browsers the file’s contents will never change while it is fresh. A long max-age already stops revalidation during normal page navigation; immutable additionally stops the conditional requests a browser sends when the user reloads the page. Firefox and Safari honour the directive. Chrome ignores it, but it does not revalidate sub-resources on a normal reload anyway.
Why Query String Cache Busting Fails on CDNs
Before touching your Nginx configs, check your HTML templates for older query-string versioning like this:
<!-- Do not use query string cache busting in production -->
<link rel="stylesheet" href="/css/app.css?v=2">
<script src="/js/app.js?v=2"></script>Query-string versioning is fragile behind CDNs and proxy layers for three reasons:
- CDN Cache Keys: Not every CDN configuration includes the query string in its cache key. If yours is set to ignore it,
?v=2and?v=3resolve to the same cached object. - Non-Atomic Deploys:
/css/app.css?v=2and/css/app.css?v=3are the same file on disk. While a deploy is rolling out, an old HTML page can be handed the new file (or the reverse), and the CDN can cache that mismatch under the wrong version. - Purge Traps: If you accidentally send an immutable header on
/css/app.css?v=2and your CDN ignores the parameter, every user gets stuck with the cached version of/css/app.cssuntil you trigger an edge purge.
You need content-hashed filenames (asset fingerprinting) like app.8f9b2c3d.css or bundle-a74e1902.js, where the hash is computed directly from the file contents during your build step.
Step 1: Put a Content Hash in Every Built Filename
Whichever build tool you use, configure it to write a hash of each file’s contents into the output filename. Vite already does this by default (assets/[name]-[hash].js). This vite.config.js, in your project root, makes the pattern explicit across scripts, stylesheets, and fonts:
import { defineConfig } from 'vite';
export default defineConfig({
build: {
// Vite 8 renamed this option to rolldownOptions; rollupOptions still works as a deprecated alias
rollupOptions: {
output: {
entryFileNames: 'assets/[name].[hash:8].js',
chunkFileNames: 'assets/[name].[hash:8].js',
assetFileNames: 'assets/[name].[hash:8].[ext]'
}
}
}
});This puts every asset into an /assets/ folder with an 8-character content hash. Run your build and list the output folder: you should see names like index.a1b2c3d4.js. If a CSS file doesn’t change between deployments, its hash stays the same, so your CDN cache stays warm across releases.
Step 2: Split Hashed Assets and HTML in Nginx
Your origin server has to send different headers depending on whether the requested file is content-hashed or mutable HTML. For the full server setup around this, see the guide to deploy Node.js on a VPS with Nginx and CDN.
Open your Nginx server block (usually /etc/nginx/sites-available/default or /etc/nginx/conf.d/app.conf) and split your caching rules into targeted location blocks:
server {
listen 80;
server_name app.example.com;
root /var/www/app/dist;
index index.html;
# 1. Hashed static assets - 1 Year Immutable Cache
location ~* "^/assets/.+\.[A-Za-z0-9_-]{8,}\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf)$" {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header X-Content-Type-Options "nosniff";
access_log off;
try_files $uri =404;
}
# 2. Un-hashed static fallback assets (favicons, robots.txt, manifests)
location ~* \.(ico|txt|xml|webmanifest|json)$ {
add_header Cache-Control "public, max-age=86400, must-revalidate";
access_log off;
try_files $uri =404;
}
# 3. HTML entry points and SPA routing - always revalidate
location / {
add_header Cache-Control "no-cache";
try_files $uri $uri/ /index.html;
}
}The asset pattern is quoted because Nginx requires that for any regex containing braces, and its hash part allows - and _ because Vite’s hashes are not hex-only. Cache-Control is set with add_header alone: per the Nginx ngx_http_headers_module documentation, expires emits its own Cache-Control: max-age header, so combining the two sends the header twice.
Step 3: Avoid the add_header Inheritance Trap
add_header directives are inherited from the parent level only if the current level defines none of its own. If you define security headers (like X-Frame-Options or CORS) in the parent http or server context, and then add add_header Cache-Control inside a location block, Nginx silently drops all the parent headers for that block.
To prevent security regressions or CORS failures on static assets, repeat the shared headers in every block that uses add_header:
# Correct pattern: include common headers across blocks
location ~* "^/assets/.+\.[A-Za-z0-9_-]{8,}\.(js|css|woff2)$" {
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Access-Control-Allow-Origin "*";
add_header X-Content-Type-Options "nosniff";
try_files $uri =404;
}If fonts on a CDN subdomain start failing with CORS errors after this change, the guide to fix CDN font CORS errors in Nginx covers the Access-Control-Allow-Origin header in detail.
Step 4: Tune CDN Rules and Prevent 404 Cascades
When you deploy a new build, it’s tempting to wipe out old build files. But if an active user has an older index.html loaded right when the deploy finishes, their browser will try to request chunks that no longer exist on your origin.
If your CDN reaches back to the origin for that missing chunk, Nginx returns a 404 Not Found. If your CDN caches that 404 for hours, the UI breaks for everyone served by that edge location.
- Keep Prior Build Assets on Origin: Don’t run
rm -rf dist/*right before copying new builds. Keep the last two or three deployment asset folders on your static storage so late-loading clients can still fetch older bundles. - Configure Origin Shielding: Prevent stampedes against your origin when cache misses spike by setting up an origin shield with request collapsing.
- Short TTL on Error Statuses: In your CDN rules, cap
404and502caching at 5 to 10 seconds. That prevents sticky outage responses.
Step 5: Test and Verify the Headers with cURL
On the server, reload Nginx with sudo nginx -t && sudo systemctl reload nginx. Then verify your headers against both the origin and the CDN edge.
Still on the server, request a hashed asset from the origin, using a real filename from your build:
curl -s -I http://127.0.0.1/assets/app.8f9b2c3d.js -H "Host: app.example.com"You should see these response headers returned:
HTTP/1.1 200 OK
Server: nginx
Content-Type: application/javascript
Cache-Control: public, max-age=31536000, immutable
X-Content-Type-Options: nosniffYour output also includes lines such as Date, Content-Length and ETag; the line that matters is Cache-Control. Now test your HTML entry point through the CDN, from your own computer, to make sure it never carries immutable directives:
curl -s -I https://app.example.com/index.htmlConfirm that Cache-Control returns no-cache. This makes browsers revalidate the HTML document on every visit, so they discover new hashed filenames straight away. Run the asset check through the CDN URL too; many CDNs also add a header showing whether the response was a cache hit.
Common Problems and Fixes
- The immutable header is missing: the request matched a different location. Check that the filename really fits the regex (8 or more hash characters before the extension), and that you reloaded Nginx.
- The CDN still shows the old max-age: it cached the old response, or an edge TTL rule overrides your origin headers. Purge the CDN cache once, and set the CDN to respect origin cache headers.
- “Expected a JavaScript module script” errors in the console: a missing file under
/assets/that does not match the hashed pattern fell through totry_files … /index.html, so the browser got HTML. Add a plainlocation /assets/ { try_files $uri =404; }block so missing assets return 404 instead. Cache-Controlappears twice: anexpiresdirective is still active for the same files. Remove it and keep onlyadd_header.
Frequently Asked Questions
What happens if I set immutable on index.html by accident?
Returning visitors stop getting frontend updates. With an immutable header and a one-year max-age, they keep the cached index.html until they clear their browser cache or the year runs out. Keep entry documents and service workers strictly on no-cache.
Does immutable work on older browsers like Safari 10 or IE11?
Browsers that don’t recognize immutable simply ignore the token and respect the standard max-age=31536000 directive. It won’t cause syntax errors or broken requests on legacy clients.
Can I use immutable caching with WordPress or monolithic CMS frameworks?
Yes, as long as your theme or asset pipeline writes file hashes or version fingerprints directly into filenames. You can configure Nginx to match asset paths like /wp-content/themes/your-theme/dist/ with immutable headers while leaving dynamic plugin assets on shorter TTLs.
Why does the browser still send requests when I hit reload?
A hard refresh (Shift + F5 or Cmd + Shift + R) instructs the browser to bypass its local cache regardless of header rules. On a standard reload you should only see a request for the HTML document: Firefox and Safari skip revalidation for immutable files, and Chrome does not revalidate sub-resources on a normal reload.
Next Steps
Deploy once with the new rules and open your browser’s Network tab: hashed assets should load from the cache on the second visit, while index.html is checked each time. To shrink those long-cached files further, see how to serve pre-compressed Brotli and gzip assets on Nginx.

