How to Serve Static Files Faster with Nginx: Expires Headers and Cache-Control

Every repeat visitor to your site downloads the same CSS, JavaScript, images, and fonts again unless you tell their browser not to. That wastes bandwidth, and on a small VPS it also wastes CPU serving files that never change. The fix is two HTTP headers, and you can set both in Nginx in about ten minutes. This guide shows how to serve static files faster with Nginx using expires headers and Cache-Control, with durations that make sense for each file type and a safe way to test the result.

Pair it with compression. A good next read is our guide on enabling gzip and Brotli compression in Nginx, since compression shrinks the first download and caching removes the repeat downloads.

What expires and Cache-Control actually do

When Nginx serves a file, it can attach headers that tell the browser how long to keep its copy before asking for a fresh one. Expires gives an absolute date. Cache-Control: max-age=... gives a duration in seconds. Modern browsers follow Cache-Control when both are present, and Nginx sets both for you when you use the expires directive. Using nginx expires headers is the simplest way to set both at once.

When the time runs out, the browser does not blindly re-download the file. It sends a conditional request with If-Modified-Since, and if the file has not changed, Nginx answers with a 304 Not Modified and no body. The file still loads from the local cache, so the page feels instant even after expiry. Long durations are safe as long as you change the file name when the content changes, which is where cache busting comes in later.

How to serve static files faster with Nginx: the two headers that matter

There are only two directives you need for most sites. The expires directive sets the lifetime, and add_header Cache-Control lets you add flags such as public and immutable. The public flag says shared caches, such as a CDN in front of your VPS, may store the file. The immutable flag tells the browser the file will never change at this URL, so it should not even send a conditional request while the cache entry is fresh. Use immutable only for files whose names include a version or content hash. Together, these two directives are the core of any nginx cache-control static files setup. A common pattern is one location block per file type, such as location ~* .(jpg|jpeg|png|webp|css|js|woff2)$, each with its own expires value.

These blocks assume your CSS, JavaScript, images, and fonts carry a version in the file name or query string. If they do not, use shorter durations until you add versioning, or you will serve stale styles to visitors after every deploy.

Pick a duration for each file type

Not every static file deserves the same lifetime. A logo that has not changed in two years can cache for a year. A JavaScript bundle that changes with every release should cache for a long time only if its name changes with every release.

File type Suggested duration Why
Images (jpg, png, webp, avif, svg) 1 year Rarely change
Fonts (woff2, woff, ttf) 1 year Almost never change
CSS and JavaScript with hashed names 1 year Each version is a new URL
CSS and JavaScript without hashed names 1 day to 1 week Deploys reach visitors soon
PDFs and downloads 1 month Change occasionally
HTML pages No long cache Caching delays every update

Notice what is missing from that table: HTML. Never put a long expires on HTML documents. The HTML file is what points the browser at the current CSS and JavaScript file names, so if the browser caches an old HTML page, it keeps requesting old assets even after you deploy new ones. Leave HTML cacheable for a few minutes at most, or do not cache it at all. If you want full-page caching for HTML, that is a different mechanism, and our guide to Nginx FastCGI cache setup covers when server-side page caching helps and when it gets in the way.

Writing the config in your server block

Add the location blocks inside the server block in your site config, usually /etc/nginx/sites-available/your-site:

server {
    listen 443 ssl;
    server_name example.com;
    root /var/www/example.com;

    location / {
        try_files $uri $uri/ =404;
    }

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

Two notes on that example. access_log off stops Nginx from logging every image request, which keeps the access log small on a busy site. And add_header in a location block replaces headers inherited from the server block, so if you set security headers at server level, repeat them inside the location block or they will disappear for static files.

After editing, test the config with sudo nginx -t before reloading, so a typo never takes the site down.

If you want a fuller walkthrough of testing config changes without downtime, see our guide on testing a new Nginx config safely.

Cache busting versioned assets so updates actually reach visitors

Long cache durations only work when a changed file gets a new URL. That practice is called cache busting, and there are two common ways to do it. The cleanest is a content hash in the file name, such as app.9f3c2a1b.css. Build tools for modern frameworks do this by default, and WordPress plugins that handle asset versioning do the same. The other way is a version query string, such as style.css?v=20261128. It works, but some older proxies ignore query strings when caching, so the file-name hash is the safer choice.

Whatever method you pick, make it automatic. A deploy step that renames files by hand will be forgotten on the one deploy where it matters, and visitors will stare at a broken layout until their cache expires. Hash the file contents and write the new name into your HTML or template at build time. That is the whole job of cache busting versioned assets: the URL changes when the bytes change, and the browser treats the new URL as a brand new file.

Testing your headers with curl

Do not trust the config file alone. Ask the server what it actually sends with curl -I https://example.com/assets/app.9f3c2a1b.css. The -I flag fetches only the headers, which is enough for this check.

Look for three lines in the output. Cache-Control: public, immutable should be there, Expires should show a date about a year ahead, and the response should be 200 on the first request. Then repeat the request with the If-Modified-Since header from the first response and confirm you get a 304 with no body. If the headers are missing, check that the request actually matches your location block. A common cause is a more specific location block earlier in the config that matches the same files and wins, or a regex that does not include the extension you are testing.

WordPress sites need one extra step

If you run WordPress behind Nginx, the file-name hash approach depends on your theme and plugins. Most well-built themes already version their CSS and JavaScript with a query string that changes on update, which is good enough for a one-week expires. For the one-year duration, look for a plugin or build step that rewrites asset names with a hash.

Images need more care. The media library serves the same file name after you replace an image, so a one-year cache means visitors keep seeing the old image. Shorten the image duration to a week, or delete and re-upload the replacement under a new name. The same caution applies to WebP and AVIF variants. If you convert images to modern formats, read our guide on serving WebP and AVIF images on WordPress with Nginx first, since the file-name rules there interact with the caching rules here.

Mistakes that break caching

The most common mistake is caching HTML for a long time and then wondering why a new post or a price change does not show up. The second is adding immutable to files whose names never change, which locks visitors into the old version for the full duration. The third is setting headers in one location block while another location block actually serves the files, so the headers never reach the browser. Curl catches all three in seconds.

What to do next

Start with one site and one file type. Add the location block for images, reload Nginx, and check the headers with curl. Then extend the same block to fonts and versioned CSS and JavaScript. Once the headers are right, make cache busting automatic in your deploy step so long durations stay safe. Repeat visitors will load most of the page from their own disk, and your VPS will serve fewer requests.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.