nginx 之缓存服务器
缓存类型:
服务端缓存
代理缓存
客户端缓存
Nginx代理缓存
配置语法
使用之前需要先定义一个proxy_cache_path
配置语法: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];
默认状态:-;
配置方法:http
proxy_cache
配置语法:proxy_cache zone | off;
默认状态:proxy_cache off;
配置方法:http、server、location
缓存过期周期
配置语法:proxy_cache_valid [code...] time;
默认状态:-
配置方法:http、server、location
缓存的维度
配置语法:proxy_cache_key string;
默认状态:proxy_cache_key $scheme$proxy_host$request_url;
配置方法:http、server、location
确保后端正常:netstat -luntp|grep 800
去到Nginx缓存服务器
upstream imooc {
server 116.62.103.228:8001;
server 116.62.103.228:8002;
server 116.62.103.228:8003;
}
proxy_cache_path /opt/app/cache levels=1:2 keys_zone=imooc_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name localhost jeson.t.imooc.io;
#charset koi8-r;
access_log /var/log/nginx/test_proxy.access.log main;
location / {
proxy_cache imooc_cache;
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";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
include proxy_params;
}
检查配置并重启
nginx -tc /etc/nginx/nginx.conf
nginx -s reload -c /etc/nginx/nginx.conf
这个时候去访问,就会在/opt/app/cache下生成缓存文件,并且访问的一直是这个页面
关闭缓存
检查并重启
清理指定的缓存
方式一:rm -rf 缓存目录内容
方式二:第三方扩展模块ngx_cache_purge
让部分页面不缓存
配置语法:proxy_no_cache string ...;
默认状态:-
配置方法:http、server、location
if ($request_uri ~ ^/(url3|login|register|password\/reset)){
set $cookie_nocahe 1;
}
location / {
proxy_cache imooc_cache;
proxy_pass http://imooc;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pargma $http__authorization;
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;
}
if ($request_uri ~ ^/(url3|login|register|password\/reset)){
set $cookie_nocahe 1;
}
location / {
proxy_cache imooc_cache;
proxy_pass http://imooc;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
proxy_no_cache $http_pargma $http__authorization;
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;
}
检查并重启
访问url1,会产生缓存,不管怎么刷新都访问这个
访问url3,则没有缓存,会进行页面更替(轮询)