Nginx 反向代理缓存服务器配置

反向代理缓存除了存储命中,还要处理绕过、过期和源站故障。以下配置适合公开只读内容。

完整缓存策略

proxy_cache_path /var/cache/nginx/site keys_zone=site_cache:100m inactive=30m;

server {
    listen 80;
    server_name www.example.com;

    location / {
        proxy_cache site_cache;
        proxy_cache_key $scheme$request_method$host$request_uri;
        proxy_cache_valid 200 5m;
        proxy_cache_bypass $http_authorization $cookie_session;
        proxy_no_cache $http_authorization $cookie_session;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
        proxy_cache_lock on;
        add_header X-Cache $upstream_cache_status always;

        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
    }
}

验证命中与绕过

curl -I http://127.0.0.1/news
curl -I http://127.0.0.1/news
curl -I -H 'Authorization: Bearer test' http://127.0.0.1/news

清理