Below are examples of how you can implement basic website caching using the .htaccess file. These examples cover both browser caching and server-side caching.
Browser Caching:
Browser caching instructs visitors' browsers to store static assets locally, reducing the need to download them with each visit. This is achieved by setting expiration headers.
apache
# Enable Expires headers
<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 image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
Server-Side Caching:
Server-side caching involves storing copies of dynamically generated pages to serve to subsequent visitors, reducing the load on your server.
apache
# Enable caching for certain file types
<FilesMatch "\.(html|htm|xml|txt|xsl)$">
FileETag None
Header set Cache-Control "max-age=7200, must-revalidate"
# Enable caching for certain media files
<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif)$">
FileETag None
Header set Cache-Control "max-age=2592000, public"
# Enable caching for scripts and stylesheets
<FilesMatch "\.(css|js)$">
FileETag None
Header set Cache-Control "max-age=2592000, public"
Note:
- Ensure that
mod_expires
and mod_headers
modules are enabled on your server. You can do this by checking your server configuration or contacting your hosting provider.
- Adjust the expiration times (
max-age
) according to your website's update frequency and the nature of your content.
- Always test these configurations on a staging environment before implementing them on a production site.
- Keep in mind that caching might cause issues if your website frequently updates content. In such cases, consider implementing cache-busting strategies or selectively excluding certain dynamic content from caching.
By incorporating these caching directives into your .htaccess file, you can significantly improve the speed and performance of your website for your users.