缓存
最后更新于
最后更新于
# 配置缓存文件 path路径
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
Default: —
Context: http
# 开启代理缓存,zone代表哪个path
Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http, server, location
# 缓存有效期配置
Syntax: proxy_cache_valid [code ...] time;
Default: —
Context: http, server, location
# 缓存维度配置,即配置key
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, locationupstream blog {
server 192.168.0.159:8080;
server 192.168.0.159:8081;
server 192.168.0.159:8082;
}
# /opt/app/cache 缓存存储路径
# levels 按照目录进行归并和分级,1:2 代表两层目录进行分级
# keys_zone 定义开辟zone空间的名称,以供下面引用,10m代表大小,1m大约可以存放8000个key
# max_size 缓存目录最大多大,用满之后就会触发淘汰规则
# inactive=60m 超过60分钟的未被访问的缓存空间,此缓存就会被移除
# use_temp_path 临时路径,建议关闭,会有不必要的性能损耗
proxy_cache_path /opt/app/cache levels=1:2 keys_zone=blog_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name localhost;
location / {
# 开启缓存,使用blog_cache zone
proxy_cache blog_cache;
proxy_pass http://blog;
# 针对200和304请求进行缓存,缓存有效期为12h
proxy_cache_valid 200 304 12h;
# 其他状态的缓存有效期配置为10分钟
proxy_cache_valid any 10m;
# 维度配置
proxy_cache_key $host$uri$is_args$args;
# 增加头信息,告诉客户端缓存是否被命中
add_header Nginx-Cache "$upstream_cache_status";
# 当某台服务器出现error、timout、500状态等情况时,就跳过此台服务器
proxy_next_upstream error timout invalid_header http_500 http_502 http_503 http_504;
include proxy_params;
}
}# 定义不将响应保存到缓存的条件。如果字符串参数的至少一个值不为空且不等于“0”,则不会保存响应
Syntax: proxy_no_cache string ...;
Default: —
Context: http, server, location# 以下配置在server块中
# 如果是登录、注册、密码重置等页面,就设置cookie nocachekey为1
if ($request_uri ~ ^/(url3|login|register|password\/reset)) {
set $cookie_nocache 1;
}
location / {
proxy_cache off;
proxy_pass http://imooc;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
add_header Nginx-Cache "$upstream_cache_status";
# 生效nocache
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pragma $http_authorization;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
include proxy_params;
}
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pragma $http_authorization;Syntax: slice size;
Default: slice 0;
Context: http, server, location