This article will guide you through controlling browser caching using the .htaccess file.
- Access Your Website's Files:
Log in to your hosting control panel or use an FTP client to manage your website's files. - Navigate to the Root Directory:
Locate and open thepublic_htmldirectory or the root directory of your website. - Edit the
.htaccessFile:
If a.htaccessfile exists, open it for editing.
If it doesn't exist, create a new file named.htaccess. - Add Cache Control Directives:
Insert the following code to set cache expiration times for various file types:# Enable mod_expires ExpiresActive On # Set default expiration time to 1 month ExpiresDefault "access plus 1 month" # Set specific expiration times for different file types 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/javascript "access plus 1 month" ExpiresByType application/font-woff2 "access plus 1 year"This configuration sets the following cache expiration times:
- Images (JPEG, GIF, PNG): Cached for 1 year.
- CSS and JavaScript files: Cached for 1 month.
- Web Open Font Format 2 (WOFF2) fonts: Cached for 1 year.
Adjust these durations as needed to balance performance and content freshness.
- Save and Upload the
.htaccessFile:
Save the changes to the.htaccessfile.
Upload the file back to the root directory if you edited it locally. - Verify the Changes:
Clear your browser cache.
Visit your website to ensure that the caching behavior aligns with your settings.
Note: Ensure that the mod_expires module is enabled on your server. If it's not enabled, you can use the mod_headers module to set cache control headers:
# Set cache control headers
Header set Cache-Control "max-age=31536000, public"
This configuration sets the Cache-Control header to cache the specified file types for 1 year.
By implementing these configurations, you can effectively control browser caching to enhance your website's performance.