Nginx 静态资源缓存设置

在开发调试web的时候,经常会碰到因浏览器缓存(cache)而经常要去清空缓存或者强制刷新来测试的烦恼,提供下apache不缓存配置和nginx不缓存配置的设置。在常用的缓存设置里面有两种方式,都是使用add_header来设置:分别为Cache-Control和Pragma。

nginx:
location ~ .*.(css|js|swf|php|htm|html )$ {
add_header Cache-Control no-store;
add_header Pragma no-cache;
}

对于站点中不经常修改的静态内容(如图片,JS,CSS),可以在服务器中设置expires过期时间,控制浏览器缓存,达到有效减小带宽流量,降低服务器压力的目的。

以Nginx服务器为例:

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
#过期时间为30天,
#图片文件不怎么更新,过期可以设大一点,
#如果频繁更新,则可以设置得小一点。
expires 30d;
}

location ~ .*.(js|css)$ {
expires 10d;
}

实例:

server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /data/web;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location ~ .*/.(css|js|swf|php|htm|html)$ {
add_header Cache-Control 'no-store';
add_header Pragma no-cache;
}
location / {
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}

}

原文地址:https://www.cnblogs.com/weifeng1463/p/7613740.html