問題描述
Apache FilesMatch ‑ 匹配正則表達式中的文件夾 (Apache FilesMatch ‑ matching a folder in the regular expression)
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
‑‑‑‑‑
參考解法
方法 1:
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.
方法 2:
<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).
方法 3:
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.
(by fistameeny、arahaya、Frank Nocke、T.Todua)