How to Bypass Cache in Nginx: Simple Configuration Guide
To bypass cache in
nginx, use the proxy_cache_bypass directive with a condition that disables caching, such as checking a request header or cookie. Alternatively, set proxy_no_cache to prevent caching of specific requests, ensuring fresh content is served.Syntax
The main directives to bypass cache in nginx are proxy_cache_bypass and proxy_no_cache. Both accept variables or conditions to control when caching is skipped.
proxy_cache_bypass <condition>;- skips cache lookup if the condition is true.proxy_no_cache <condition>;- prevents storing the response in cache if the condition is true.
Common conditions include checking headers like $http_cache_control or cookies.
nginx
proxy_cache_bypass $http_cache_control; proxy_no_cache $http_cache_control;
Example
This example shows how to bypass cache when the client sends the header Cache-Control: no-cache. It uses proxy_cache_bypass and proxy_no_cache with the $http_cache_control variable.
nginx
location / {
proxy_cache my_cache;
proxy_cache_valid 200 10m;
# Bypass cache if client sends 'Cache-Control: no-cache'
proxy_cache_bypass $http_cache_control = "no-cache";
proxy_no_cache $http_cache_control = "no-cache";
proxy_pass http://backend_server;
}Common Pitfalls
Common mistakes when bypassing cache in nginx include:
- Using only
proxy_cache_bypasswithoutproxy_no_cache, which skips cache lookup but still stores the response in cache. - Not matching the exact header or condition, causing cache to be used unintentionally.
- Forgetting to define or enable
proxy_cachezones properly.
Always test with appropriate headers and verify cache behavior.
nginx
location / {
proxy_cache my_cache;
# Wrong: only bypass cache lookup
proxy_cache_bypass $http_cache_control = "no-cache";
proxy_pass http://backend_server;
}
# Correct way:
location / {
proxy_cache my_cache;
proxy_cache_bypass $http_cache_control = "no-cache";
proxy_no_cache $http_cache_control = "no-cache";
proxy_pass http://backend_server;
}Quick Reference
| Directive | Purpose | Typical Usage |
|---|---|---|
| proxy_cache_bypass | Skip cache lookup for requests | proxy_cache_bypass $http_cache_control = "no-cache"; |
| proxy_no_cache | Prevent storing response in cache | proxy_no_cache $http_cache_control = "no-cache"; |
| $http_cache_control | Variable for Cache-Control header | Used in conditions to detect no-cache requests |
Key Takeaways
Use both proxy_cache_bypass and proxy_no_cache to fully bypass caching in nginx.
Check client headers like Cache-Control to decide when to bypass cache.
Without proxy_no_cache, responses may still be cached even if lookup is bypassed.
Test cache bypass by sending requests with appropriate headers.
Ensure proxy_cache zones are properly configured before using cache directives.