How to Use add_header for Cache Control in Nginx
Use the
add_header directive in your Nginx configuration to set cache control headers like Cache-Control. Place it inside the server or location block to specify caching rules for responses.Syntax
The add_header directive sets HTTP headers in Nginx responses. It has this syntax:
add_header name value [always];
name is the header name, like Cache-Control.
value is the header value, such as no-cache or max-age=3600.
The optional always flag ensures the header is added even on error responses.
nginx
add_header Cache-Control "max-age=3600, public";Example
This example shows how to set cache control headers to cache static files for 1 hour:
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
add_header Cache-Control "public, max-age=3600";
}
}Output
When a client requests a file under /static/, the response includes the header:
Cache-Control: public, max-age=3600
Common Pitfalls
One common mistake is forgetting the always flag, which means headers won't be added on error responses like 404 or 500.
Another is placing add_header inside a block that does not match the request, so headers are not applied.
nginx
location / {
# Wrong: header not 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 |
|---|---|---|
| add_header | Sets HTTP response header | add_header Cache-Control "no-store, no-cache, must-revalidate"; |
| always | Forces header on all responses | add_header Cache-Control "no-cache" always; |
| Cache-Control | Controls browser caching | "public, max-age=3600" |
| location block | Scope where header applies | location /images/ { add_header Cache-Control "max-age=86400"; } |
Key Takeaways
Use
add_header Cache-Control "value"; inside server or location blocks to control caching.Add the
always flag to ensure headers are sent on error responses.Place
add_header in the correct block matching your requests to apply headers properly.Common cache control values include
no-cache, no-store, and max-age.Test your configuration by checking response headers with browser DevTools or curl.