How to cache static content on Nginx?

Here in this post I’ll show you how to cache static content or files on Nginx. If you are not caching static content yet, tune it now, you’ll gain more speed just doing it.

Nginx

I’m assuming that you know the configuration directories and files of nginx and we can set the parameters in an http (multi-site way) or a server block(single-site way).

location ~* \.(css|gif|jpg|js|png)$ {
    access_log off;
    expires max;
}
  • You can add more file extensions by using PIPE Symbol “|” as a divider.
  • The access log is turned “Off” for small performance gain.
  • The expires is set to “Max”, static content will be cached for a long time.

Once you have added this block, just save it, test nginx, and reload nginx web server.

nginx -t
systemctl reload nginx

I always recommend testing nginx first before reloading or restarting the nginx to avoid any downtime due to an error in typing the syntax.

Now you can try out loading your website few times in the browser and you can notice speed is improved as most of the static part is loading for the very first time and onwards it just loads a unique segment of the page.

Below is a small video of a test page we made for the sake of this tutorial, watch out for the difference between loading a website uncached and cached environments.

In the above setup, I’ve just added CSS, JavaScript, and few image file formats. That is more than enough for most of the blogs or basic websites, but you can add more.

For your convenient I have listed all the known and usable static files here:

bmp|class|css|csv|doc|docx|ejs|eot|eps|gif|ico|jar|jpeg|jpg|js|mid|midi|otf|pdf|pict|pls|png|ppt|pptx|ps|svg|svgz|swf|tif|tiff|ttf|webp|woff|woff2|xls|xlsx

I hope this will be useful.

Published by AtulHost

Creator of AtulHost. An ardent Linux user. Comes from a business management background. Loves to do research on modern business insights and technological solutions.

Leave a reply

Required fields are asterisked and email address will not be shared.