nginx添加proxy_cache模块做缓存服务器

时间:2022-05-07 06:55:56

业务需求nginx对后端tomcat(静态文件)做缓存 减轻后端服务器的压力

nginx添加proxy_cache模块做缓存服务器

# 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")

 #定义缓存目录
proxy_temp_path /data/proxy_temp_dir;
proxy_cache_path /data/proxy_cache_dir levels=: keys_zone=cache_one:200m inactive=1d max_size=30g;
 #虚拟主机中配置 student.conf

 server {
listen ;
server_name student.metasequoia.com; access_log /var/log/nginx/student_access.log cache;
error_log /var/log/nginx/student_error.log ; location ~ /purge(/.*) #(测试 必须写在location上面 否则刷新不成功 why)
{
allow ip;#(写成127.0.0.1时 测试不生效 why)(所以写成主机ip)
deny all;
proxy_cache_purge cache_one $host$$is_args$args;
} location ~ .*\.(gif|jpg|jpeg|png|bmp|ico|js|css)$ {
proxy_cache cache_one;
proxy_cache_valid 12h;
proxy_cache_key $host$uri$is_args$args;
#expires 30d;
add_header X-Cache $upstream_cache_status; include /usr/local/nginx/vhost/proxy.configure;
proxy_pass http://student_server;
} location / {
include /usr/local/nginx/vhost/proxy.configure;
proxy_pass http://student_server;
}
 #定义日志
log_format cache '$remote_addr [$time_local] "$request" '
'"$upstream_status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" '
'"$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