htaccess / mod_expires - caching specific files

Sharcoux picture Sharcoux · Nov 28, 2014 · Viewed 10.5k times · Source

Ok, I checked a lot of websites about how to manage the browser's cache memory with a .htaccess file, but it is still very not clear to me.

I want to cache specific files for one month. For the rest, I want it to be refreshed every time. So I tried:

<IfModule mod_headers.c> 
    Header unset Cookie
    Header unset Set-Cookie
    Header unset Cache-Control
    Header unset ETag
    FileETag none 
</IfModule>

<IfModule mod_expires.c>  
    ExpiresActive On
    ExpiresDefault "now"
    <Files "/css/jquery-ui.css">
      ExpiresDefault "access plus 1 month"
    </Files>
    <Files "/js/jquery-1.10.2.min.js">
      ExpiresDefault "access plus 1 month"
    </Files>
    <Files "/js/jquery-ui.js">
      ExpiresDefault "access plus 1 month"
    </Files>
    <Files "/js/analytics.js">
      ExpiresDefault "access plus 1 month"
    </Files>
    <Files "/matheos/img/*">
      ExpiresDefault "access plus 1 month"
    </Files>
    <Files "/img/*">
      ExpiresDefault "access plus 1 month"
    </Files>
</IfModule>

But it doesn't work exactly as expected...

The HTML is correctly not cached, but the specific files like jquery-ui.css, which should be cached for 1 month, are also not cached.

Anyway, does this .htaccess seem ok for you ?

Answer

Sharcoux picture Sharcoux · Dec 1, 2014

Ok, got it ! To target a specific file, the correct syntax is :

# to not cache css except jquery-ui.css
ExpiresByType text/css "now"
<FilesMatch "jquery-ui\\.css$">
    ExpiresByType text/css "access plus 1 month"
</FilesMatch>

This is the only way that worked for me, at least in the case of an ovh shared host. I also tried all possible combinations with ExpiresDefault but it didn't work...