How to Set Cache Expiration in Nginx for Efficient Caching
To set cache expiration in
nginx, use the expires directive inside a location or server block to specify how long browsers should cache content. For example, expires 1d; sets the cache to expire after one day.Syntax
The expires directive controls the cache expiration time sent in the Cache-Control and Expires headers. It is used inside location, server, or http blocks.
expires time;— sets the cache duration (e.g.,1dfor one day,10mfor ten minutes).expires off;— disables caching.expires epoch;— sets expiration to a date in the past, effectively disabling caching.
nginx
location /images/ {
expires 30d;
}Example
This example sets cache expiration for static files like images and CSS to 30 days, improving load speed by telling browsers to reuse cached files for that time.
nginx
server {
listen 80;
server_name example.com;
location /images/ {
expires 30d;
add_header Cache-Control "public";
}
location /css/ {
expires 7d;
add_header Cache-Control "public";
}
location / {
expires off;
}
}Common Pitfalls
Common mistakes when setting cache expiration in Nginx include:
- Not using
add_header Cache-Controlalong withexpires, which can cause inconsistent caching behavior. - Setting too long expiration for dynamic content, causing users to see outdated data.
- Placing
expiresoutside of a valid block likelocationorserver, which makes it ineffective.
nginx
location /api/ {
expires 30d; # Wrong: API responses usually should not be cached this long
}
# Correct approach:
location /api/ {
expires off;
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
}Quick Reference
| Directive | Description | Example |
|---|---|---|
| expires | Sets cache expiration time | expires 10m; |
| expires off | Disables caching | expires off; |
| expires epoch | Expires immediately (past date) | expires epoch; |
| add_header Cache-Control | Controls cache behavior explicitly | add_header Cache-Control "public"; |
Key Takeaways
Use the
expires directive inside location or server blocks to set cache expiration.Combine
expires with add_header Cache-Control for consistent caching behavior.Avoid long cache times for dynamic content to prevent stale data.
Use
expires off; to disable caching when needed.Place cache directives correctly inside valid Nginx blocks for them to work.