nginx配置缓存模块及清理缓存办法
1、nginx配置缓存模块
下载、编译安装
# wget https://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
# ./configure --user=www --group=www --add-module=/opt/ngx_cache_purge-2.3 --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
# make
# make install
# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.8.0
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC)
TLS SNI support enabled
configure arguments: --user=www --group=www --add-module=/opt/ngx_cache_purge-2.3 --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
2、修改nginx配置如下:
分别在http区域、server区域修改
http{
...........................................
proxy_connect_timeout 60;
proxy_read_timeout 60;
proxy_send_timeout 60;
proxy_temp_path /data/proxy_nginx/temp;
proxy_cache_path /data/proxy_nginx/cache levels=1:2 keys_zone=cache_wap:500m inactive=1d max_size=30g;
#设置Web缓存区名称为cache_wap,内存缓存空间大小为500MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。
levels=1:2 表示缓存目录的第一级目录是1个字符,第二级目录是2个字符,即/data/proxy_nginx/cache/a/1b这种形式
}
server {
location ~ /purge(/.*)
{
allow 127.0.0.1;
allow 192.168.1.8;
deny all;
proxy_cache_purge cache_wap $host$1$is_args$args;
}
# 注意,此处如果加的位置不对,可能影响清除缓存功能,必须加在location上方
location ~ \.(gif|jpg|jpeg|png|bmp|ico)$ {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://127.0.0.1:8080;
proxy_cache cache_wap; #设置资源缓存的zone
proxy_cache_key $host$uri$is_args$args; #设置缓存的key,以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
proxy_cache_valid 200 304 12h; #对不同的HTTP状态码设置不同的缓存时间
expires 7d; #缓存时间
}
location / {
proxy_pass https://wap_services;
proxy_http_version 1.1;
proxy_connect_timeout 120;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_buffer_size 256k;
proxy_buffers 4 256k;
proxy_ignore_client_abort on;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_wap; #设置资源缓存的zone
proxy_cache_valid 200 304 12h; #对不同的HTTP状态码设置不同的缓存时间
proxy_cache_key $host$uri$is_args$args; #设置缓存的key,以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内
}
}
3、手动清除指定url缓存功能
假如要清除https://192.168.1.10/xxxx/images/video/top.jpg图片
只需要访问https://192.168.1.10/purge/xxxx/images/video/top.jpg
就可以成功清除了
评论