Last active
July 29, 2020 03:48
-
-
Save stonecorleone/33dabf2eb397717c774f80b10e4fc66a to your computer and use it in GitHub Desktop.
Make Browsers Cache Static Files With mod_expires On Apache2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Enabling mod_expires | |
a2enmod expires | |
Configuring mod_expires | |
If you have multiple file types that should expire after the same time after they have been accessed (let's say in one week), | |
you can use a combination of the FilesMatch and the ExpiresDefault directives, e.g. as follows: | |
<IfModule mod_expires.c> | |
<FilesMatch "\.(jpe?g|png|gif|js|css)$"> | |
ExpiresActive On | |
ExpiresDefault "access plus 1 week" | |
</FilesMatch> | |
</IfModule> | |
This would tell browsers to cache .jpg, .jpeg, .png, .gif, .js, and .css files for one week. | |
Instead of using FilesMatch and ExpiresDefault directives, you could also use the ExpiresByType directice | |
and set an Expires header (plus the max-age directive of the Cache-Control HTTP header) individually for each file type, | |
e.g. as follows: | |
<IfModule mod_expires.c> | |
ExpiresActive on | |
ExpiresByType image/jpg "access plus 60 days" | |
ExpiresByType image/png "access plus 60 days" | |
ExpiresByType image/gif "access plus 60 days" | |
ExpiresByType image/jpeg "access plus 60 days" | |
ExpiresByType text/css "access plus 1 days" | |
ExpiresByType image/x-icon "access plus 1 month" | |
ExpiresByType application/pdf "access plus 1 month" | |
ExpiresByType audio/x-wav "access plus 1 month" | |
ExpiresByType audio/mpeg "access plus 1 month" | |
ExpiresByType video/mpeg "access plus 1 month" | |
ExpiresByType video/mp4 "access plus 1 month" | |
ExpiresByType video/quicktime "access plus 1 month" | |
ExpiresByType video/x-ms-wmv "access plus 1 month" | |
ExpiresByType application/x-shockwave-flash "access 1 month" | |
ExpiresByType text/javascript "access plus 1 week" | |
ExpiresByType application/x-javascript "access plus 1 week" | |
ExpiresByType application/javascript "access plus 1 week" | |
</IfModule> | |
You might have noticed that I've set three ExpiresByType directives for Javascript files - that is because Javascript files | |
might have different file types on each server. If you set just one directive for text/javascript, but the server recognizes | |
the Javascript file as application/javascript, then it will not be covered by your configuration, and no cache headers will be set. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment