http之缓存
http之缓存
http缓存的作用
HTTP缓存主要用在对一些实时性要求不高的静态文件进行的缓存,往往都是存在浏览器端,防止这些“多余”的请求重复的访问服务器,对服务器造成压力,从而提高网站的性能。
效果
**第一次请求 **
状态码
响应头信息
请求头信息
效率
第二次请求
状态码发生改变 从200变为304 可以理解为从缓存中取出
响应头
请求头
效率
何时需要缓存呢?
缓存应该存在多长时间
实战
1.我们可以利用apache的expires扩展来控制html,css等文件是否缓存和缓存周期
apache文档有详细介绍
ExpiresDefault "<base> [plus] {<num> <type>}*"
ExpiresByType type/ encoding "<base> [plus] {<num> <type>}*"
ExpiresDefault 是设置默认的缓存参数
ExpiresByType 是按照文件类型来设计独特的缓存参数
2..htaccess文件
# 配置mod_expires模块
<IfModule mod_expires.c>
# 启用有效期控制
ExpiresActive On
# image
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
# css/js
ExpiresByType text/css "access plus 4 weeks"
ExpiresByType text/javascript "access plus 4 weeks"
</IfModule>
如何不设置缓存
在http中有cache-controll字段可以设置缓存时间和缓存对象
`ache-control` 可设置的字段值有:
- private :客户端可以缓存
- public :客户端和代理服务器都可缓存,大部分情况可以认为public和private是一样的
- max-age=xxx : 缓存的内容将在 xxx 秒后失效 (时间就是在这儿设置的)
- no-cache :需要使用另外一种http缓存策略来验证缓存数据
- no-store :所有缓存策略都不会进行(这里指的是两种缓存策略都不会进行)
./htaccess
<FilesMatch "\.(gif)$">
header set Cache-Control "no-store,must-revalidate"
</FilesMatch>
效果

http思维导图


浙公网安备 33010602011771号