欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

nginx缓存配置和ngx_cache_purge总结

程序员文章站 2022-04-07 19:26:43
...
nginx缓存配置首先设定一个cache日志的格式,可以在日志中查看“MISS”和“HIT”状态log_format cache '***$time_local ' '***$upstream_cache_status ' '***Cache-Control: $upstream_http_cache_control ' '***Expires: $upstream_http_expires ' '***"$request" ($status) ' '***"$http_user_agent" ';其次设定缓存参数
proxy_connect_timeout 5;proxy_read_timeout 60;proxy_send_timeout 5;proxy_buffer_size 16k;proxy_buffers 4 64k;proxy_busy_buffers_size 128k;proxy_temp_file_write_size 128k;#注:temp_path和cache_path 指定的路径必须在同一分区proxy_temp_path/cache/temp_dir;#设置Web缓存区名称为cache_one,内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。proxy_cache_path /cache/cache levels=1:2 keys_z max_size=30g;#设定一个upstream
upstream appserver {server 192.168.10.5;}#用于清除缓存,假设一个URLhttp://192.168.10.3/test.txt,通过访问http://192.168.10.3/purge/test.txt就可以清除该URL的缓存。此功能需要手动编译模块ngx_cache_purge,下载地址为http://labs.frickle.com/files/,最好用最新版本,本例中为2.1。 location ~ /purge(/.*) { #设置只允许指定的IPIP段才可以清除URL缓存。 allow 127.0.0.1; allow 192.168.10.0/24; deny all; proxy_cache_purge cache_one $host$1$is_args$args; } #注意,此规则必须放于purge之后,因为放之前就会优先匹配到此规则,会在清除缓存的时候报404错误。location ~ .*\.(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {proxy_pass http://appserver;proxy_redirect off;#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内proxy_cache_key $host$uri$is_args$args; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr;proxy_cache cache_one;#对不同的HTTP状态码设置不同的缓存时间proxy_cache_valid 200 302 1h;proxy_cache_valid 301 1d;proxy_cache_valid any 1m;expires 30d;#可以再cache.log日志中看到 MISSHIT状态access_log/usr/local/nginx/logs/cache.log cache;}配置完成,重新启动nginx,不能reload。随便访问一个页面http://192.168.10.3/9.jpg,在/cache/cache下面也会生成相应的缓存文件
查看cache.log,可以看到第一次访问为MISS,第二次为HIT
***19/Mar/2014:10:48:16 +0800 ***MISS ***Cache-Control: - ***Expires: - ***"GET /9.jpg HTTP/1.1" (200) *** #后面浏览器信息就省略了
***19/Mar/2014:10:48:37 +0800 ***HIT ***Cache-Control: - ***Expires: - ***"GET /9.jpg HTTP/1.1" (304) ***
清除缓存访问 http://192.168.10.3/purge/9.jpg,看到如下信息说明缓存已被清除。

Successful purge


Key : 192.168.10.3/9.jpg

Path: /cache/cache/6/c1/368f9db143996c9f865921f8b2c94c16

以上就介绍了nginx缓存配置和ngx_cache_purge总结,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。