This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.
In order to follow this guide, you should have a server with Ubuntu 18.04.4 LTS access to sudo privileges and Nginx.
How to fix Leverage browser caching on WordPress using Nginx, on this mini tutorial I will show how to fix this SEO performance killer.
ssh onto your server and issue the following commands:
cd /etc/nginx/sites-available/
and then open your website .conf file
nano your_website_name_conf file
Then add the following inside a server block:
#browser caching of static assets location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 7d; add_header Cache-Control "public, no-transform"; }
Now save it and exit from your text editor. The code above is basically telling the server that the file types are not going to change during the next 7 days, this process will make any return visit to your website faster because it won’t need to download the resources again.
You will need to restart the Nginx server you just need to run the following command.
service nginx restart
That’s it. You have now Leveraged Browser Caching of your static assets.
This code snippet will inform the user’s browser to cache assets for seven days. If the users return on day two they are served with a cached version of the website. If they return after the seven days the browser will request the latest version.
The code snippet version applies a seven-day cache to all assets however you may not need to change assets as frequently or want to change more often than that. For example, let’s say your CSS and javascript only changes once a week so there is no point forcing the user to download a new cache version of the website every day, therefore, we can create a separate directive for CSS and JS only.
#browser caching of static assets location ~* \.(jpg|jpeg|png|gif|ico)$ { expires 7d; }
#browser caching of css and js location ~* \.(css|js)$ { expires 7d; }
By enforcing users to download new assets every time they visit the web site is not a good practice, it wastes bandwidth resources and if they are browsing on their phones it will consume their allowance data.
This quick-fix will instantly boost your website speed. We can run it through Google page speed and we will see a score increase from the score before without the code snippet. That is the real win here as it sends a strong signal to Google that you care about website quality and user experience and they will reward you with better rankings as a result.