缓存配置
#vim /usr/local/nginx/conf/nginx.conf
upstream node {
server 192.9.191.31:8081;
server 192.9.191.31:8082;
}
proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name www.test.com;
index index.html;
location / {
proxy_pass http://node;
proxy_cache cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
}
}
参数详解
proxy_cache_path /soft/cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
#proxy_cache //存放缓存临时文件
#levels //按照两层目录分级
#keys_zone //开辟空间名,10m:开辟空间大小,1m可存放8000key
#max_size //控制最大大小,超过后Nginx会启用淘汰规则
#inactive //60分钟没有被访问缓存会被清理
#use_temp_path //临时文件,会影响性能,建议关闭
proxy_cache cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
#proxy_cache //开启缓存
#proxy_cache_valid //状态码200|304的过期为12h,其余状态码10分钟过期
#proxy_cache_key //缓存key
#add_header //增加头信息,观察客户端respoce是否命中
#proxy_next_upstream //出现502-504或错误,会跳过此台服务器访问下一台服务器
3.创建缓存目录
mkdir /cache
nginx -t
nginx -s reload
清除缓存
- rm删除已缓存的数据
rm -rf /cache/* - 通过ngx_cache_purge扩展模块清理,需要编译安装nginx
部分页面不缓存
- nginx配置
#vim /usr/local/nginx/conf/nginx.conf
upstream node {
server 192.9.191.31:8081;
server 192.9.191.31:8082;
}
proxy_cache_path /cache levels=1:2 keys_zone=cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name www.test.com;
index index.html;
if ($request_uri ~ ^/(static|login|register|password)) {
set $cookie_nocache 1;
}
location / {
proxy_pass http://node;
proxy_cache cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pargma $http_authorization;
}
}
2 .重启加验证
nginx -t
nginx -s reload
统计日志命中率
- 日志格式:变量$upstream_cache_status"
#vim /usr/local/nginx/conf/nginx.conf
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$upstream_cache_status"';
access_log logs/access.log main;
error_log logs/error.log;
- 统计日志命中率加入到计划任务中这里省略
awk '{if($NF = "HIT"){count++;}} END{printf "%.2f%",count/NR*100}' /usr/local/nginx/logs/access.log