NGINX缓存代理配置后始终返回MISS的原因咨询
X-Proxy-Cache: MISS in Your NGINX Configuration Let’s dive into why you’re consistently seeing X-Proxy-Cache: MISS and walk through fixes step by step:
1. Cache-Control Headers Might Be Bypassing the Cache
Your configuration includes proxy_cache_bypass $http_cache_control;, which tells NGINX to skip the cache entirely if the client sends a Cache-Control header with directives like no-cache, no-store, or max-age=0 (common in refresh requests).
- Test this by forcing a cache-friendly request header:
If this returnscurl -I -H "Cache-Control: max-age=3600" https://example.comX-Proxy-Cache: HITon the second request, your original requests were sending headers that bypassed the cache. - You can also strip the
Cache-Controlheader entirely to test:curl -I https://example.com -H "Cache-Control:"
2. Cache Directory Permissions Could Be Blocking Writes
NGINX needs write access to the /tmp/nginx directory you specified for caching. If the user running NGINX (typically nginx or www-data) doesn’t have permissions here, it can’t store cache files at all.
- Check the directory permissions:
ls -ld /tmp/nginx - Fix permissions if needed (adjust the user/group to match your NGINX setup):
chown -R nginx:nginx /tmp/nginx systemctl restart nginx
3. Backend Responses Might Be Preventing Caching
Even if NGINX is configured to cache, it won’t store responses that include headers like Cache-Control: private, Cache-Control: no-cache, or Expires: 0.
- Inspect the raw response from your backend to check for these headers:
curl -I http://127.0.0.1:8000 - If you want to override these backend headers, add
proxy_ignore_headers Cache-Control Expires;to your location block to force NGINX to cache the response regardless.
4. Cache Key or Configuration Precedence Issues
Your proxy_cache_key ("$scheme://$host$uri") only uses the protocol, host, and path—this is fine for static content without query parameters, but double-check:
- Are you accessing URLs with query parameters (e.g.,
?id=123) that aren’t included in the cache key? While this would cause shared caching, it shouldn’t result in consistent MISS. - Is there a more specific
locationblock in your config that’s matching your requests instead of the one with caching enabled? NGINX uses the most specific location match first.
5. Test with a Minimal Cacheable Endpoint
To rule out backend-specific issues, create a simple test location that returns static content:
location /test-cache { proxy_cache my_zone; proxy_cache_key "$scheme://$host$uri"; proxy_cache_valid 200 10m; add_header X-Proxy-Cache $upstream_cache_status; return 200 "Test Cache Content"; }
Restart NGINX, then visit https://example.com/test-cache twice. If the second request returns X-Proxy-Cache: HIT, your core cache configuration works, and the problem lies with your backend’s response headers.
内容的提问来源于stack exchange,提问作者maxisme

