Beginner Fundamentals
Caching Static Assets
Browsers can store files locally so they do not download them again on every visit. You control this with cache headers, and Nginx makes them easy to set for static assets.
The expires Directive
expires sets how long a browser may reuse a cached file. It writes the Cache-Control and Expires headers for you:
location ~* \.(css|js|png|jpg|gif|ico|woff2)$ {
expires 30d;
}
This tells browsers to cache these asset types for 30 days. During that time, repeat visits load them instantly from disk.
Choosing a Duration
- Frequently changing files: short, like
1h. - Stable assets: long, like
30dor1y. - Files with a version in the name (
app.a1b2c3.js): use1ysafely, since a change produces a new name.
location ~* \.(woff2|ttf|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
immutable tells the browser the file will never change, so it skips revalidation entirely.
Avoid Caching HTML
HTML usually links to your latest assets, so it should not be cached aggressively:
location = /index.html {
add_header Cache-Control "no-cache";
}
Why It Matters
Good caching cuts server load and makes returning visits feel instant. The rule of thumb: cache versioned assets for a long time and keep HTML fresh.