Set a Maximum Age in .htaccess

For a hand coded HTML website adding expiry dates to each referenced file: CSS; js or image can be done as a part of the development.

For a dynamic CMS website adding expiry dates to the included images on pages and posts is less easy and may become frustrating.

I chose to seek an alternative approach to adding expiry dates to the referenced image, one that didn’t require the editing of each entry.

The approach I chose to investigate, was to make use of the .htaccess file.

With the below code added to the file the age expiry for the images is configured:

<FilesMatch "\.(bmp|class|doc|docx|eot|exe|ico|json|mdb|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|pot|pps|ppt|pptx|svg|svgz|swf|tif|tiff|ttf|ttc|_ttf|wav|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|BMP|CLASS|DOC|DOCX|EOT|EXE|ICO|JSON|MDB|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|POT|PPS|PPT|PPTX|SVG|SVGZ|SWF|TIF|TIFF|TTF|TTC|_TTF|WAV|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW)$">
<IfModule mod_headers.c>
Header set Cache-Control "max-age=604800, public"
</IfModule>
</FilesMatch>

In the example shown the expiry age of 604800 is the equivalent of a week.

This approach is somewhat blunt, one configuration setting for all of these file types. I could replicate the above splitting the FilesMatch, replicating the code but targeting, for example, just the images or documents.

However, by using the global configuration it does mean that adding it to an individual image won’t be forgotten.

Overall whilst this does the job, meeting the requirement to provide ageing of the referenced files, I think the approach lacks subtlety. Its a once-size fits all approach.