Apache FilesMatch - matching a folder in the regular expression
Asked Answered
T

3

22

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

Tollhouse answered 15/5, 2009 at 11:13 Comment(0)
V
31

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.

Viscountess answered 16/5, 2009 at 13:16 Comment(1)
Thanks very much for your help. I'll go for the multiple .htaccess files to save changing the main httpd.conf. Thanks again, MattTollhouse
C
21

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

Caves answered 20/12, 2017 at 14:57 Comment(0)
P
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.

Platter answered 22/8, 2016 at 18:25 Comment(1)
I feel like an idiot been trying to do this all day... Read your response and was like DUH! that would be so simple. Thanks!Versatile

© 2022 - 2024 — McMap. All rights reserved.