Nginx WEB服务端缓存配置
在nginx的日常使用中,运维人员经常设置Nginx的静态资源缓存,或者设置nginx的静态资源分离发布,来减少后端动态容器的负担。Nginx缓存在使用以及配置方面更加简单易用,当然,你也可以使用其它的缓存容器来缓存页面上的静态资源,比如: Squid Cache等等
Nginx的Web缓存服务主要由proxy_cache相关指令集和fastcgi_cache相关指令集构成,使用ngx_cache_purge模块来进行缓存代理。
1、编译时,添加ngx_cache_purge模块:
wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar -zxvf ngx_cache_purge-2.3.tar.gz
./configure --prefix=/app/nginx --with-http_stub_status_module --with-http_ssl_module --add-module=../ngx_cache_purge-2.3
make && make install
2、配置:
proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=nginx_cache:200m inactive=1d max_size=10g;
# 设置Web缓存区名称为nginx_cache
# 缓存目录为/tmp/nginx_cache
# 内存缓存空间大小为200MB
# 每天清除一次缓存,硬盘缓存空间大小为30GB。
# levels=1:2 表示缓存目录的第一级目录是1个字符,第二级目录是2个字符,
# 即/tmp/nginx_cache/cache1/a/1b这种形式
upstream www {
server 10.10.1.1:8133;
}
server {
listen 80;
listen 443;
server_name www.lingyepro.com;
ssl on;
ssl_certificate tmp.crt;
ssl_certificate_key tmp.key;
location ~ \.(gif|jpg|jpeg|png|bmp|ico|js|css)$ {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass https://www;
proxy_set_header Via "nginx";
proxy_cache nginx_cache; #设置资源缓存的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://www;
#proxy_set_header Host $host:443;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Via "nginx";
client_max_body_size 200m;
if ($scheme = 'http'){
return https://$host$uri;
}
}
access_log /usr/local/nginx/logs/repo.log;
client_max_body_size 100m;
}
此时查看Nginx进程会发现多出缓存进程:
3、验证
查询缓存目录/tmp/nginx_cache发现多出多个缓存文件:
注意:缓存的目的在于降低后端WEB容器的负担,在版本变更频繁的情况下,缓存容易造成脏读的情况,所以,当变更版本后最好清空缓存目录下已经存在的缓存文件。
Nginx WEB服务端缓存配置
https://www.lingyepro.com/archives/122