How to Cache Static Content in NGINX


cache static content in nginx

NGINX allows you to speed up your website performance by caching static files such as CSS, JS, and image files. It does that by storing these files on user’s web browser when they visit your site the first time. So every time they visit your website, they are served these files directly from their web browser and only other files are server from your server. Here’s how you can cache static content in NGINX.

 

How to Cache Static Content in NGINX

Here are the steps to cache static content in NGINX

 

It’s actually quite easy. If you have a single site and use the default NGINX configuration, then open the config file in a text editor

 


$ sudo nano /etc/nginx/sites-available/default

 

If you use NGINX to run multiple websites, and have set virtual host for each site, then open the configuration file of your individual websites.

 

Scroll down to the bottom of the 1st server section and add the following lines


location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  expires 365d;
}

The above code will cache jpg, jpeg, png, gif, ico, css and js files. You can modify it according to your requirement.

 

Save and close the file

 

Restart NGINX Server

Reload NGINX server with new configuration to apply the changes. Whenever you make any changes to /etc/sites-available/ you need to reload/restart NGINX server.


$ sudo systemctl reload nginx.

 

 

Test NGINX Cache

To test your configuration, install the HTTP Header Live browser extension and open one of your static files (css, js, images, etc) that you have cached.

If your page is cached properly, it will show you the Expires and Cache-Control header with a max-age directive.

how to cache static file in nginx

 

NGINX provides plenty of configuration options making it a very flexible web server. Even if your website is fast, you should still try to caching with NGINX. Since the content is served directly from users’ web browser, it will not only reduce your web server load but also reduce data bandwidth for your website, thereby reducing server data & server costs.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!