21

I'm trying to cache some files using a .htaccess file for Apache2. I want to cache a particular folder longer than anything else, so i've been trying to use the FilesMatch directive like this:

<FilesMatch "skins(.*)\.(jpg|png|gif)">
ExpiresDefault A2592000
</FilesMatch>

I'm hoping to be able to cache all image files in the /skins/ directory and it's subdirectories. However, I can't quite get the regular expression to work - Apache just ignores it altogether.

How do you match a folder with <FilesMatch> in a .htaccess file?

Cheers,
Matt

fistameeny
  • 1,048
  • 2
  • 14
  • 27

3 Answers3

30

FilesMatch should only match filenames. You can place the .htaccess file inside the skins directory and it should look something like this:

<FilesMatch "\.(jpg|png|gif)">
    ExpiresDefault A2592000
</FilesMatch>

Alternatively, in httpd.conf, you could use:

<Directory path_to_the_skins_dir>
    <FilesMatch "\.(jpg|png|gif)">
        ExpiresDefault A2592000
    </FilesMatch>
</Directory>

Good luck.

jamix
  • 5,484
  • 5
  • 26
  • 35
arahaya
  • 1,010
  • 9
  • 11
  • Thanks very much for your help. I'll go for the multiple .htaccess files to save changing the main httpd.conf. Thanks again, Matt – fistameeny May 19 '09 at 16:02
20

<Directory> and <Location> are disallowed in .htaccess, but…

You can use <If> which is allowed also in the “Context“ .htaccess (not just httpd.conf)… also see here. It allows you to match for a base path and an extension and anything else, a RegExp can grasp…

Tested and working:

<If "%{REQUEST_URI} =~ m#^/_stats/.*\.(jpg|png|css|js)#">
    Header unset ETag
    FileETag None

    ExpiresActive On
    ExpiresDefault "access plus 1 day"
</If>

Notes: _stats is my rewrite url, not the incoming URL (if that makes any difference on your end), not sure, why the matching works against that…

# is just a different outside “gate” to indicate a regular expression, instead of using / to mark it as a regular expression. (Since I need to use / in its literal sense, this saves me from having to escape the /'s).

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Frank N
  • 9,625
  • 4
  • 80
  • 110
11

Directory and Location commands don't work in .htaccess on many shared hostings. The solution could be to create .htaccess in target sub-folder, and use FilesMatch command there.

T.Todua
  • 53,146
  • 19
  • 236
  • 237