禁止浏览器缓存的方法

最近做一个修改CSS的小项目,每次修改都需要删除浏览器缓存才能更新,于是就想把Apache设置一下,禁止浏览器缓存。

在网上找了一下,其实就是在响应头里添加禁止浏览器缓存的内容就行。

其基本内容如下:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

其中,Cache-Control用于HTTP1.1(包括1.1)以上;Pragma用于HTTP1.0;Expires用于代理服务器缓存。

各种语言的写法如下:

PHP

header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

Java(JSP)

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0"); 

ASP.NET

Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");

ASP

Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate"
Response.addHeader "Pragma", "no-cache"
Response.addHeader "Expires", "0"

Ruby

response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"

Python

response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"

HTML

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

Apache

<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

Apache的情况下,可以加到.htaccess文件里,也可以直接加到httpd.conf里。

禁止Apache静态文件缓存

线上如果缓存静态文件能够提高服务器性能和用户体验,但是在开发阶段,如果开启静态文件缓存,不利于开发测试

有时候更改了静态文件,发现页面不起作用,然后清空了浏览器缓存页面也不起作用。每次必须重启apache服务器才可以,最终想到可能是静态文件缓存导致的。

关闭apache静态文件缓存只需要更改httpd.conf,注释掉如下扩展

#LoadModule expires_module modules/mod_expires.so
#LoadModule headers_module modules/mod_headers.so

在页面中设置如下属性

<meta http-equiv=”pragma” content=”no-cache”>
附 nginx静态文件设置方法 nginx的conf中

#静态数据保存时效
location ~ .html$ {
proxy_pass http://www.hello.com;
proxy_redirect off;
proxy_cache cache_one;
#此处的cache_one必须于上一步配置的缓存区域名称相同
proxy_cache_valid 200 304 12h;
proxy_cache_valid 301 302 1d;
proxy_cache_valid any 1m;
#不同的请求设置不同的缓存时效
proxy_cache_key $uri$is_args$args;
#生产缓存文件的key,通过4个string变量结合生成
expires 30d;
#其余类型的缓存时效为30天
proxy_set_header X-Forwarded-Proto $scheme;
}

原文地址:https://www.cnblogs.com/js1314/p/13157521.html