禁止瀏覽器緩存的方法


最近做一個修改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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM