Nginx的静态资源缓存

王守钰 2020-03-05 09:03:55

配置nginx.conf

##缓存配置Start##
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;
##设置临时目录
proxy_temp_path /usr/local/nginx/nginx_cache_temp;
##设置缓存目录为二级目录,共享内存区大小,非活动时间,最大容量,注意临时目录,要跟缓存目录在同一个分区
proxy_cache_path /usr/local/nginx/nginx_cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=1g;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;
###缓存配置End##

配置server

location ~ .*\.(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {
    proxy_set_header        X-Forwarded-Proto  $scheme;
    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://tomcat;
    proxy_redirect off;     
    #设置缓存共享内存区块,也就是keys_zone名称。
    proxy_cache cache_one;
    #设置http状态码为200,302缓存时间为1小时。
    proxy_cache_valid 200 302 1h;
    proxy_cache_valid 301 1d;
    proxy_cache_valid any 1m;
    #设置失期时间,为30天
    expires 30d;
}