0
0
NginxHow-ToBeginner · 3 min read

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, or location blocks depending on scope.
  • Common values include no-cache, no-store, max-age=seconds, and public.
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_header inside the correct block can cause headers to not be sent.
  • Using add_header with if blocks incorrectly may prevent headers from applying.
  • Remember that add_header only works on successful responses (status 200, 204, 301, 302, 304). For other statuses, use add_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

DirectiveDescriptionExample Value
add_header Cache-ControlSets cache-control header"max-age=3600, public"
max-ageTime in seconds to cache3600
no-cacheForces revalidationno-cache
no-storePrevents cachingno-store
publicMarks response as cacheable by any cachepublic
privateMarks response as cacheable only by browserprivate
must-revalidateForces cache to revalidate after expirymust-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.