How to Set Cache-Control Header in Nginx for Efficient Caching
To set the
cache-control header in Nginx, use the add_header Cache-Control directive inside a server, location, or http block. This header controls how browsers cache your content, improving load times and reducing server load.Syntax
The add_header directive sets HTTP headers in Nginx responses. To set the cache-control header, use:
add_header Cache-Control "value";— sets the cache-control header with the specified value.- Place it inside
http,server, orlocationblocks depending on scope. - Common values include
no-cache,no-store,max-age=seconds, andpublic.
nginx
add_header Cache-Control "max-age=3600, public";Example
This example shows how to set the cache-control header to cache static files for 1 hour in a specific location.
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
add_header Cache-Control "max-age=3600, public";
}
}Output
When a client requests a file under /static/, the response includes the header:
Cache-Control: max-age=3600, public
Common Pitfalls
- Not placing
add_headerinside the correct block can cause headers to not be sent. - Using
add_headerwithifblocks incorrectly may prevent headers from applying. - Remember that
add_headeronly works on successful responses (status 200, 204, 301, 302, 304). For other statuses, useadd_header ... always;in newer Nginx versions.
nginx
location / {
# Wrong: header won't be added on error responses
add_header Cache-Control "no-cache";
}
location / {
# Correct: header added always
add_header Cache-Control "no-cache" always;
}Quick Reference
| Directive | Description | Example Value |
|---|---|---|
| add_header Cache-Control | Sets cache-control header | "max-age=3600, public" |
| max-age | Time in seconds to cache | 3600 |
| no-cache | Forces revalidation | no-cache |
| no-store | Prevents caching | no-store |
| public | Marks response as cacheable by any cache | public |
| private | Marks response as cacheable only by browser | private |
| must-revalidate | Forces cache to revalidate after expiry | must-revalidate |
Key Takeaways
Use
add_header Cache-Control "value"; inside http, server, or location blocks to set caching rules.Common cache-control values include
max-age, no-cache, no-store, public, and private.Add
always to add_header to ensure headers are sent on all response codes.Place the directive carefully to apply caching only where needed, such as static files.
Test your configuration by checking response headers with browser DevTools or curl.