Nginx缓存服务

开启简单的缓存配置,只需要两个指令:proxy_cache_path和proxy_cache。

proxy_cache_path配置缓存的存放地址和其他的一些常用配置,

proxy_cache指令是为了启动缓存。

缓存配置

[root@proxy ~]# cat /etc/nginx/conf.d/proxy_cache.conf 
upstream cache { 
    server 192.168.1.1:80;
    server 192.168.1.2:80;
    server 192.168.1.3:80;
}
#proxy_cache 存放缓存临时⽂文件
#levels 按照两层目录分级
#keys_zone 开辟空间名  10m为大小 1m可以大约存放8000个key
#max_size 控制最大大小 超过后会启动淘汰规则
#inactive 60分钟没有被访问缓存会被清理理
#use_temp_path       临时⽂文件, 会影响性能, 建议关闭
proxy_cache_path /var/cache levels=1:2 keys_zone=code_cache:10m max_size=10g inact ive=60m use_temp_path=off;
server {  
         listen 80;
         server_name www.jcwit.com;
  location  / {
 #proxy_cache 开启缓存
 # proxy_cache_valid 状态码为200 304缓存一天其他缓存半小时
 #proxy_cache_key 缓存key
 #add_header 增加头部信息
 #proxy_next_upstream 出现502-504或错误, 会跳过此台服务器器访问下台
 proxy_pass http://cache;
 proxy_cache code_cache;
 proxy_cache_valid 304 1d;
 proxy_cache_valid  any 30m;
 add_header Nginx-Cache "$upstream_cache_status";
 proxy_next_upstream error timeout invalid_header http_500 http_502 http_503  http_504;
 include proxy_params;
 }
 }
```       

## 缓存的清理

方法1 直接删除缓存目录

方法2 使用ngx_cache_purge

下载ngx_cache_purage

wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz


重新编译nginx 

./configure –add-module=./ngx_cache_purge-2.3


修改配置文件增加刷新缓存访问路径

location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
proxy_cache_purge code_cache $host$1$is_args$args;
}


使用的时候直接该路径后接要刷新缓存的路径

### 缓存日志格式化

log_format main ‘$http_user_agent’ ‘$request_uri’ ‘$remote_addr - $remote_user [$ time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘“$http_user_agent” “$http_x_forwarded_for”‘ ‘“$upstream_cache_status”‘;
```


Nginx缓存服务
http://www.jcwit.com/article/45/
作者
Carlos
发布于
2019年7月14日
许可协议