How to Enable Caching in NGINX

enable caching in nginx

NGINX is a powerful web server that provides plenty of useful features. Its caching not only improves website speed & performance but also reduces server load. Here’s how to enable caching in NGINX.


How to Enable Caching in NGINX

Here are the steps to enable caching in NGINX.


1. Open NGINX config file

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf. If it is located at a different folder, please update it in the command below.

$ sudo vim /etc/nginx/nginx.conf


If you have multiple sites hosted, then open the virtual host file, generally located at /etc/nginx/sites-available/default or within a website’s specific virtual host config file.


2. Enable Caching in NGINX

You can easily enable caching using expires directive. If you want to cache static files, add the following lines to your config file.

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

The above code will cache static files on your website for 30 days.

If you want to only cache all files in a specific folder, for example, all .jpg files in a folder,

location ~* /uploads/(.+\.jpg)$ {
  expired 30d;


If you only want to cache a specific URL,

location ~* /specific-url-to-page$ {
 expired 30d;


3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload


That’s it! NGINX will automatically cache your content.

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!