Nginx一样能够用来做为缓存服务;客户端浏览器缓存咱们称之为客户端缓存,后端使用Redis、Memcache等缓存服务咱们称之为后端缓存,同理Nginx做为缓存服务咱们就称之为代理缓存。
Syntax:proxy_cache_path path [levels=levels][use_temp_path = on|off] keys_zone=name:size [inactive = time]nginx
[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];cookie
Default:--url
Context:httpspa
Syntax:proxy_cache zone|off;Default:proxy_cache off;3d
Context:http、server、location代理
Syntax:proxy_cache_valid [code...] time;Default:--
Context:http、server、location
Syntax:proxy_cache_key string;Default:proxy_cache_key $schema$proxy_host$request_uri; // 协议+主机+url
Context:http、server、location
http { ...... proxy_cache_path /var/cache levels=1:2 keys_zone=test_cache:10m max_size=10g inactive=60m use_temp_path=off; #60m是指60分钟,1:2两级目录,test_cache开辟的空间名称 server { listen 80; server_name localhost; access_log /var/logs/access.log main; location / { proxy_cache test_cache; 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"; # 增长头信息 key(Nginx-Cache) value($upstream_cache_status) proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; # 当出现5xx,超时,错误等时,跳过直接访问下一台服务器 include proxy_params; } } }
使用第三方模块ngx_cache_purge来实现。
Syntax:proxy_no_cache string ...;Default:---;
Context:http、server、location;
server { ...... if ($request_uri ~ ^/(login|register|password\/reset)) { set $cookie_nocache 1; } location / { proxy_cache test_cache; 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_pragma $http_authorization; add_header Nginx-Cache "$upstream_cache_status"; # 增长头信息 key(Nginx-Cache) value($upstream_cache_status) proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; # 当出现5xx,超时,错误等时,跳过直接访问下一台服务器 include proxy_params; } }
优点:每一个子请求收到的数据都会造成一个独立的文件,一个请求断了,其余请求不受影响。
缺点:当文件很大时或者slice很小时,可能会致使文件描述符耗尽等状况。