How to Set Expires Header in Nginx for Cache Control
To set the
expires header in Nginx, use the expires directive inside a location or server block. This directive controls how long browsers cache static files by specifying a time duration or a date.Syntax
The expires directive sets the caching time for responses. It accepts values like off, epoch, max, or a time duration such as 30d (30 days), 1h (1 hour), etc.
Example parts:
expires 30d;— cache for 30 daysexpires off;— disable cachingexpires max;— cache for maximum time (about 10 years)
nginx
location /images/ {
expires 30d;
}Example
This example sets the expires header to 7 days for all files in the /static/ folder. Browsers will cache these files for one week, reducing server load and speeding up page loads.
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
expires 7d;
}
}Output
When a browser requests a file under /static/, the response header will include: Expires: <date 7 days in the future>
Common Pitfalls
Common mistakes when setting the expires header include:
- Placing the
expiresdirective outside alocationorserverblock, which causes errors. - Using incorrect time formats like
30daysinstead of30d. - Not reloading Nginx after changes, so the new settings don't apply.
- Setting very long cache times for files that change often, causing stale content.
nginx
location /assets/ {
expires 30days; # Incorrect, should be 30d
}
# Correct:
location /assets/ {
expires 30d;
}Quick Reference
| Directive | Meaning | Example |
|---|---|---|
| expires off; | Disable caching | expires off; |
| expires epoch; | Set expiry to 1 Jan 1970 (immediate expiry) | expires epoch; |
| expires max; | Set expiry to maximum (about 10 years) | expires max; |
| expires 1h; | Cache for 1 hour | expires 1h; |
| expires 30d; | Cache for 30 days | expires 30d; |
Key Takeaways
Use the
expires directive inside location or server blocks to control caching.Specify cache duration with time units like
d for days or h for hours (e.g., expires 7d;).Avoid very long cache times for frequently updated files to prevent stale content.
Always reload Nginx after changing configuration to apply new settings.
Use
expires off; to disable caching when needed.