By default in an Amazon Lightsail LAMP image, the Apache HTTP server is not configured with browser caching directives enabled. Specifically, the mod_expires Apache module is not loaded. If you’re not familiar with browser caching directives, this module controls the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. These inform the browser how long to cache responses. If a resource is mostly static and doesn’t change very often, then the directive should establish a longer caching period vs. a resource that may be changing hourly. This directive reduces bandwidth consumption and server load while improving user experience by loading screens faster since the browser isn’t repeatedly requesting the same file.
Log into the Amazon Lightsail server and edit the httpd.conf file. In this example, the httpd.conf file is located in /opt/bitnami/apache/conf/ so you may need to adjust the path depending on your image.
sudo vim /opt/bitnami/apache/conf/httpd.conf
Find the mod_expires.so entry in the file, remove the comment (#), and save the file. The server does not need to be restarted.
LoadModule expires_module modules/mod_expires.so
In the .htaccess file for your site, you can add various Expires directives for relevant file types. This example provides a small sample of common file types and can be expanded to meet your particular needs. Please adjust the expiry times as appropriate for your site. A more detailed walkthrough of .htaccess files can be found at Hardening WordPress Security Using .htaccess.
<IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" ExpiresByType text/html "access plus 0 seconds" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType text/css "access plus 1 month" <IfModule mod_headers.c> Header append Cache-Control "public" </IfModule> </IfModule>
As a demonstration of the directive in action, PNG image files are set to a one year cache from the time the file is accessed. In the following image, a file accessed on June 24, 2021 (date) expires in the cache one year later on June 24, 2022 (expires). This information can be viewed in most browsers using the Inspect feature and activating the Network Monitor.
The browser also shows that the file was transferred from the cache and no additional bandwidth was consumed for that resource.