I want to cache all images for 1 month and it works great but the problem is when I try to exclude a subdirectory from caching.
So there are images on:
/ (base dir)
/IMG/
/IMG/folder/
IMG/BIG/
so all images need to be cached, but i want to make it to not cache images that are on IMG/BIG/ folder
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
</IfModule>
the above code works but when
i try this code to exclude /IMG/BIG then it doesn't work
<Directory "/IMG/BIG">
<FilesMatch "\.(jpg|png)$">
<IfModule mod_expires.c>
ExpiresActive Off
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
</FilesMatch>
</Directory>
I want to fix this in the .htaccess that is in the root folder and not by adding another .htaccess inside /IMG/big folder
CodePudding user response:
ExpiresByType image/jpg "access plus 1 month"
Aside: The correct mime-type for JPEG files is image/jpeg
, not image/jpg
, so the above probably isn't doing anything.
The <Directory>
directive is not permitted in .htaccess
- this should have resulted in a 500 Internal Server Error (the details of which would be in your server's error log).
The <IfModule>
wrappers are not required, unless you intend to use the same config on multiple servers where mod_expires and/or mod_headers are not enabled (unlikely).
To target everything else except the /IMG/BIG
subdirectory then you can use an <If>
expression and check against the REQUEST_URI
server variable with a negated regex (!~
operator). For example:
<If "%{REQUEST_URI} !~ m#^/IMG/BIG/#">
ExpiresActive on
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
</If>
To specifically override any headers for requests to /IMG/BIG/
then you could add an <Else>
directive:
<Else>
<FilesMatch "\.(jpg|png)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</FilesMatch>
</Else>
Unless there are other file types in the /IMG/BIG/
directory that you might want cached then you could remove the <FilesMatch>
container.