apache 配置 Expire/Cache-Control 头

apache 配置 Expire/Cache-Control 头

这里我使用的是Apache2.4.17

打开apache安装目录,找到conf目录,用记事本打开httpd.conf 文件。

ctrl+f 查找 LoadModule expires_module modules/mod_expires.so
去掉前面 #号!

在文本最后面添加:

<IfModule expires_module>
    
    #打开缓存
    ExpiresActive on 
    #css文件缓存7200000/3600/24=83天
    ExpiresByType text/css A7200000

    #js文件缓存83天
    ExpiresByType application/x-javascript A7200000
    ExpiresByType application/javascript A7200000

    #html文件缓存83天
    ExpiresByType text/html A7200000

    #图片文件缓存83天
    ExpiresByType image/jpeg A7200000
    ExpiresByType image/gif A7200000
    ExpiresByType image/png A7200000
    ExpiresByType image/x-icon A7200000
    
  </IfModule>

上面开启的是expire

下面是cache-control
在文本后面继续添加

<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf)$">
   Header set Cache-Control "max-age=604800, public"
</FilesMatch>

<FilesMatch ".(css|js)$">
   Header set Cache-Control "max-age=604800, public"
</FilesMatch>

这里时间设置不一样是为了检验是否成功配置的,因为,没设cache-control的时候,它会自动根据expire的时间设置自己。

最后重启apache服务器,ok!

这里说一个自己爬的坑吧!(那就是如果不出现 200 form cache, 而是出现了304,那是因为,你刷新了浏览器。。。想要出现 200 form cache,需要在浏览器地址栏里按回车键。)

也就是说:刷新浏览器 触发 304, 地址栏回车触发 200 form cache。

查了好久才发现了,之前一直想不通,既然设置了cache-control和expire为啥还是304,这就是原因,就是这么简单。。。

原文地址:https://www.cnblogs.com/zhoudaxiaa/p/8670522.html