How to Cache a website with a .htaccess file?
Caching a website using the .htaccess
file is a common practice to improve performance and reduce server load by storing static resources in the visitor’s browser. This is often achieved by setting directives for cache control and expiration headers. Below are instructions on how to use the .htaccess
file to enable caching for different types of resources.
Enable Browser Caching:
apache
# Enable browser caching for images
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg “access plus 1 year”
ExpiresByType image/png “access plus 1 year”
ExpiresByType image/gif “access plus 1 year”
ExpiresByType image/svg+xml “access plus 1 year”
ExpiresByType text/css “access plus 1 month”
ExpiresByType text/javascript “access plus 1 month”
ExpiresByType application/javascript “access plus 1 month”
ExpiresByType application/x-javascript “access plus 1 month”
ExpiresByType image/x-icon “access plus 1 year”
</IfModule>
This code sets expiration times for various types of files (images, stylesheets, scripts, etc.) so that the browser caches them and doesn’t request them from the server on every visit.
Leverage Browser Caching:
apache
# Leverage browser caching
<IfModule mod_headers.c>
<FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$”>
Header set Cache-Control “max-age=31536000, public”
</FilesMatch>
<FilesMatch “\.(xml|txt)$”>
Header set Cache-Control “max-age=3600, public, must-revalidate”
</FilesMatch>
<FilesMatch “\.(html|htm|php)$”>
Header set Cache-Control “max-age=60, private, must-revalidate”
</FilesMatch>
</IfModule>
This code sets cache control headers for different types of files, specifying how long the browser should cache them. Adjust the max-age
values based on your specific caching requirements.
Gzip Compression:
apache
# Enable Gzip Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>
Enabling Gzip compression can significantly reduce the size of files sent from the server to the client, improving website loading times.
Note:
- Ensure that your server has the required modules enabled.
mod_expires
,mod_headers
, andmod_deflate
are commonly used for these purposes. - Always make a backup of your
.htaccess
file before making changes. - Test your website thoroughly after implementing caching to ensure that all resources load correctly.
These configurations provide a good starting point, but you may need to adjust them based on your specific website setup and requirements.