Adding expires headers to your WordPress website will tell the browser to cache files and serve them directly from the browser instead of making a request to the server. In expires headers, we define a period of time that the browser can cache certain types of files and serve them. This will greatly improve the performance of your website because every time a repeated visitor makes a request, the files cached in the browser will be served leaving the webserver alone. So many page speed test tools will show you a recommendation as “Add Expires Headers” to encourage you to optimize your website. So here is how you can add it.
To add expires headers on Apache, add these lines to your .htaccess file placed in your WordPress root folder.
<IfModule mod_expires.c>
ExpiresActive On
# Images
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
# Video
ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType video/mpeg "access plus 1 year"
# CSS, JavaScript
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
# Others
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>
If you are running an NGINX server, add the following in your site configuration file.
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|svg)$ {
expires 365d;
}
location ~* \.(pdf|html|swf)$ {
expires 90d;
}
Be sure to restart your web server to see the changes. Rerun the tests and you should see the add expires header recommendation is gone.
You can change the expiry period to something else as per your requirements. But always be sure that you don’t set it for too long or too low. Always research before making changes to your expires headers, or generally, anything that goes inside your server configuration files.