Add Expires Headers for Specific Images
Asked Answered
S

2

9

All of the expires headers articles I've looked at give more or less the following solution:

ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000

But it doesn't make sense to me because I know which of my images are going to change and which aren't, so I want to be able to add specific expiration dates to specific image files. How would I go about this?

Swansdown answered 24/3, 2010 at 15:8 Comment(0)
H
10

You can use a FilesMatch, eg.

<FilesMatch "\.(js|css)$">
  ExpiresActive on 
  ExpiresDefault "access plus 1 month"
</FilesMatch>

Or for some specific files:

<FilesMatch "^(example.js|sample.css)$">
  ExpiresActive on 
  ExpiresDefault "access plus 1 month"
</FilesMatch>
Housemaid answered 24/3, 2010 at 15:14 Comment(4)
Could you give an example of how to apply this to a specific image file: example.jpg ? Thanks!Swansdown
Thanks for your help ar, much appreciated: So would the following work? (image.jpg|anotherImage.png|backgroundImage.png|bannerImg.jpg)Swansdown
Adding this code to my .htaccess gave me a 500 internal server error.Swansdown
@a'r: I think you need to escape the dot <FilesMatch "^(example\.js|sample\.css)$"> and it might be worth adding also Header append Cache-Control "public" read more: https://mcmap.net/q/360909/-how-to-make-static-content-on-apache-be-cached-by-browser-and-not-checked-for-freshness-with-every-requestQuotidian
C
3

Note that using ExpiresDefault for specific files will not work if you already used ExpiresByType. You need to use ExpiresByType again.

So this will NOT work (service-worker.js would still have +1 year expiry):

<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"
    ExpiresByType application/javascript                "access plus 1 year"
    <FilesMatch "^(service-worker.js)$">
        ExpiresDefault                                  "access plus 0 seconds"
    </FilesMatch>
</IfModule>

But this will work (service-worker.js will have +0 seconds expiry):

<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"
    ExpiresByType application/javascript                "access plus 1 year"
    <FilesMatch "^(service-worker.js)$">
        ExpiresByType application/javascript            "access plus 0 seconds"
    </FilesMatch>
</IfModule>

You might also use Header unset Expires. This would remove Expires header no matter what was set above it. You should also modify (or remove) Cache-Control header. It seems that mod_expires sets both.

    <FilesMatch "^(service-worker.js)$">
        Header unset Expires
        Header set Cache-Control "max-age=0"
    </FilesMatch>
Calkins answered 29/3, 2018 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.