htaccess / mod_expires - caching specific files
Asked Answered
R

1

8

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 ?

Rene answered 28/11, 2014 at 13:54 Comment(0)
R
10

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...

Rene answered 1/12, 2014 at 10:10 Comment(3)
Why add two backslashes in the middle of the css file's path? Is that an escape character unique to htaccess files?Passerine
Yes, because the dot is a special character in regexRene
you don't need the double escape httpd.apache.org/docs/current/mod/core.html#filesmatchRoughage

© 2022 - 2024 — McMap. All rights reserved.