skip to Main Content

Currently, my cache policy looks like this:

<IfModule mod_headers.c>    
  <FilesMatch ".(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>

And this caches my css files for 8 days. If I wanted to cache a specific file for a year, how would I do this? I saw this answer, so I tried doing this:

<IfModule mod_headers.c>    
  <FilesMatch ".(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "bootstrap.(css)$">
   Header set Cache-Control "max-age=31536000"
  </FilesMatch>
</IfModule>

As well as this just in case apache applies rules on a first come first serve basis (<- probably an incorrect use of the phrase):

<IfModule mod_headers.c>    
  <FilesMatch "bootstrap.(css)$">
   Header set Cache-Control "max-age=31536000"
  </FilesMatch>
  <FilesMatch ".(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>

But when I run the page through page speed insights, the cache policy of the bootstrap.css file remains the same. I’ve also cleared my own cache, opened an incognito tab, and checked the cache policy inside the network tab of the dev tools and the cache policy for the bootstrap file is still 8 days.

2

Answers


  1. There are two ways you can achieve this. One is that you mentioned here. Actually max-age is a parameter which tells the browser after how many seconds it should expire. So you can calculate the number of seconds for 1 year which will be “31557600”

    Another simple way is to achieve this:

    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access 1 year"
    ExpiresByType image/jpeg "access 1 year"
    ExpiresByType image/gif "access 1 year"
    ExpiresByType image/png "access 1 year"
    ExpiresByType text/css "access 1 month"
    ExpiresByType text/html "access 1 month"
    ExpiresByType application/pdf "access 1 month"
    ExpiresByType text/x-javascript "access 1 month"
    ExpiresByType application/x-shockwave-flash "access 1 month"
    ExpiresByType image/x-icon "access 1 year"
    ExpiresDefault "access 1 month"
    </IfModule>
    
    Login or Signup to reply.
  2. <Files> and <FilesMatch> sections are processed in the order they appear in the configuration files, which means that the last one applied will take precedence, so your first try should work:

    <IfModule mod_headers.c>    
      <FilesMatch ".(css)$">
       Header set Cache-Control "max-age=691200"
      </FilesMatch>
      <FilesMatch "bootstrap.(css)$">
       Header set Cache-Control "max-age=31536000"
      </FilesMatch>
    </IfModule>
    

    I have tested it and it works as expected:

    $ curl -s -v example.com/bootstrap.css 2>&1 | grep Cache-Control
    < Cache-Control: max-age=31536000
    
    $ curl -s -v example.com/foo.css 2>&1 | grep Cache-Control
    < Cache-Control: max-age=691200
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search