相应的配置做了注释,并提示了注意事项。
nginx.conf
# 配置缓存目录 /data/nginx/cache,必须确保目录存在,并且nobody用户可以写入(这里假设以nginx以nobody用户运行)
# sudo -u nobody touch /data/nginx/cache/test 测试目录可用
# keys_zone 配置的是缓存元数据的内存大小,max_size 是缓存所用磁盘大小
# inactive 的含义是2h内没有访问的cache,被自动清除
# use_temp_path=off upstream过来的响应直接写入缓存目录,避免二次拷贝
proxy_cache_path /data/nginx/cache levels=2:2 keys_zone=content_cache:512m max_size=10g inactive=2h use_temp_path=off;
conf.d/test.cache.conf
# cache
server {
listen 80;
# 必须为on,否则cache不生效
proxy_buffering on;
# 方便查看缓存是否生效,也可以把这个加入access log,方便统计
add_header X-Cache-Status $upstream_cache_status;
# cache 使用的 key
proxy_cache_key $proxy_host$request_uri;
location /t1 {
# 返回200的请求被缓存120小时
proxy_cache_valid 200 120h;
proxy_cache content_cache;
rewrite /t1/(.+)$ /$1 break;
proxy_pass http://127.0.0.1:9090;
}
location /t2 {
# 返回200的请求被缓存,缓存时间由upstream控制
proxy_cache_valid 200 0h;
proxy_cache content_cache;
rewrite /t2/(.+)$ /$1 break;
proxy_pass http://127.0.0.1:9090;
}
}
# upstream
server {
listen 9090;
default_type "text/plain";
location /static {
return 200 "CACHED-STATIC@$request_uri";
}
location /max-age {
add_header Cache-Control "max-age=86400";
return 200 "CACHED-MAX-AGE@$request_uri";
}
}