Search code examples
.htaccesshttp-headerscache-control

Set different cache controls for files of the same extension using .htaccess


I am new to using .htaccess file. I have image files; a.jpeg & several other .jpeg files in the same folder. What I want the client to do is cache a.jpeg but not the rest of .jpeg files.

Here's what my .htaccess file looks like:

#exception
<Files a.jpeg>
Header set Cache-Control "max-age=604800, public"
</Files>

# NEVER CACHE - rest of .jpegs
<FilesMatch "\.(jpg|jpeg)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>

The problem is that a.jpeg is not being cached like all other .jpegs. Kindly help.

The webiste that I am using to test my cached and non-cached files is this : https://www.giftofspeed.com/cache-checker/


Solution

  • I just came to know that the <FilesMatch ""> expects a regular expression to search for a file hence the regex : "\b^(?!a)\w*\.jpg\b" inside the FilesMatch tag worked.

    Here's the complete .htaccess file :

    # NEVER CACHE - rest of .jpegs
    <FilesMatch "\b^(?!a.jpg)\w*\.jpg\b">
    Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
    </FilesMatch>