nginx添加proxy_cache模块做缓存服务器
业务需求nginx对后端tomcat(静态文件)做缓存 减轻后端服务器的压力
# nginx-1.6.2.tar.gz ngx_cache_purge-2.3.tar.gz
#编译安装
./configure --add-module=../ngx_cache_purge-2.3 --prefix=/usr/local/nginx --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module
make && make install
#安装ngx_cache_purge后 必须重启nginx才能生效(reload无效 报错 unknown directive "proxy_cache_purge")
1 #定义缓存目录 2 proxy_temp_path /data/proxy_temp_dir; 3 proxy_cache_path /data/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
1 #虚拟主机中配置 student.conf 2 3 server { 4 listen 80; 5 server_name student.metasequoia.com; 6 7 access_log /var/log/nginx/student_access.log cache; 8 error_log /var/log/nginx/student_error.log ; 9 10 location ~ /purge(/.*) #(测试 必须写在location上面 否则刷新不成功 why) 11 { 12 allow ip;#(写成127.0.0.1时 测试不生效 why)(所以写成主机ip) 13 deny all; 14 proxy_cache_purge cache_one $host$1$is_args$args; 15 } 16 17 location ~ .*\.(gif|jpg|jpeg|png|bmp|ico|js|css)$ { 18 proxy_cache cache_one; 19 proxy_cache_valid 200 304 12h; 20 proxy_cache_key $host$uri$is_args$args; 21 #expires 30d; 22 add_header X-Cache $upstream_cache_status; 23 24 include /usr/local/nginx/vhost/proxy.configure; 25 proxy_pass http://student_server; 26 } 27 28 location / { 29 include /usr/local/nginx/vhost/proxy.configure; 30 proxy_pass http://student_server; 31 } 32 33
1 #定义日志 2 log_format cache '$remote_addr [$time_local] "$request" ' 3 '"$upstream_status" $body_bytes_sent "$http_referer" ' 4 '"$http_user_agent" ' 5 '"$upstream_addr" "$upstream_response_time" $upstream_cache_status'; #$upstream_cache_status 定义浏览器中的缓存状态 HIT MISS EXPIRED
#example
http://student.metasequoia.com/resource/images/login13.png
清除缓存
curl student.fclassroom.com/purge/resource/images/login13.png