Fix Leverage Browser Caching in WordPress

Purpose of Code Snippet

Web browsers like Google Chrome, Safari, Firefox and Microsoft Edge cache the static files on your webpage. This will help browsers to speed up loading your content when the user visits the pages on your site next time. This is technically called browser caching. In order for the browsers to cache your static files, you have to tell them how many days they should keep the cache on the visitors computer.

The static files include images, stylesheets, JavaScript files, icons and any other file types you serve on your site.

Template to Edit

Insert the below code snippet in your .htaccess file.

Code Snippet

Copy and paste the following code snippet at the bottom of your htaccess file. It contains the most used static file types on common WordPress sites and inform the browsers to keep the cache for the specified period. If you have any other static file like PDF, make sure to include in this list.

## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg "access 1 year" 
ExpiresByType image/jpeg "access 1 year" 
ExpiresByType image/gif "access 1 year" 
ExpiresByType image/png "access 1 year" 
ExpiresByType text/css "access 1 month" 
ExpiresByType application/pdf "access 1 month" 
ExpiresByType text/x-javascript "access 1 month" 
ExpiresByType application/x-shockwave-flash "access 1 month" 
ExpiresByType image/x-icon "access 1 year" 
ExpiresDefault "access 2 days" 
## EXPIRES CACHING ##

Problem with Long Cache Period

We have used 1 year and 1 month for keeping the cache on the browser. You can change the time period, in case if you update the content on your site frequently. Otherwise, long caching period may cause the old content loaded on the browser if the user did not cleanup the cache on the browser.

RELATED:  How to Disable and Limit WordPress Post Revisions?

Article last updated on November 17, 2020

Leave a Comment