How to configure MOD_EXPIRES headers

What is mod_expires?

Mod_expires is an Apache module that will instruct web browsers on how to control the cache. With the mod_expires values, you will tell web browsers how long to keep images, HTML files etc. Such settings will result in faster page loading times on subsequent requests from the same user.

This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

Apache Help
apache
Apache mod_expires page

To verify that the expires module is loaded, use:

httpd -M | grep expires
#[root@web /]# httpd -M | grep expires
 expires_module (static)
[root@web /]#

How to configure mod_expires rules?

Mod_expires rules can be configure in the .htaccess file from your site’s root directory. An example is:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"

#default expiry time
ExpiresDefault "access plus 2 days"
</IfModule>

You can use this as a template. Add or remove MIME types per your needs.

The idea is to configure each MIME type you want to be cached. Start each line with ExpiresByType followed by MIME type and by time period. For more information check the documentation at Apache Module mod_expires

How to test if mod_expires is working?

If you have SSH access, use the curl command to access a file from the site:

curl -is https://example.com/file

Example accessing a png file:

[root@web /]# curl -is https://demo.plothost.com/logo.png
HTTP/2 200
date: Wed, 19 May 2021 14:40:22 GMT
server: Apache/2
last-modified: Tue, 12 Feb 2013 23:58:37 GMT
etag: "244c-4d58fcdd26540"
accept-ranges: bytes
content-length: 9292
cache-control: max-age=31536000
expires: Thu, 19 May 2022 14:40:22 GMT
content-type: image/png

[root@web /]#

As you can see the server is instructing the client to cache this file till 19 May 2022 (one year from the present – date: field in the result).

Resources:
How to get the loaded Apache modules

Leave a Reply