How to enable browser caching in NGINX

Caching will improve speeds and browsing. Once the data is stored, visitors to your website will have a better experience as they will be able to move through your site faster. Also this is a great way to render CSS, JS, Image files from client browser without sending request to the web server.

Steps to enable leverage browser caching in NGINX.

1. Open NGINX Server configuration

Run the following command to open NGINX server configuration file:

$ sudo vim /etc/nginx/nginx.conf

If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/conf.d/website.conf then open its configuration with the following command:

$ sudo vim /etc/nginx/conf.d/website.conf
2. Enable Leverage Browser Caching.

Add the following 3 lines in your NGINX server configuration file to cache static content in NGINX.

expires 7d;
add_header Pragma "public";
add_header Cache-Control "public";

The first line instructs NGINX to cache content in client browser for 7 days (7d). You can change this cache duration as per your requirement. After this period, any new request from user will result in cache re-validation and update from the client browser.

The next two lines are used to set cache related headers.

You can place the below lines in location , server or http blocks. 

location /static/ {
 expires 7d;
 add_header Pragma "public";
 add_header Cache-Control "public";
}

In the above case, only requests to /static/ will be cached.

In case you want to cache specific file types (like js, jpg, css, etc.), you can do so by using location block.

location ~* \.(js|jpg|jpeg|gif|png|css|tgz|gz|doc|pdf|ppt|tar)$ {
 expires 7d;
 add_header Pragma "public";
 add_header Cache-Control "public";
}

Similarly, you can place cache configuration in server block before any location block. In this case, all responses from this server will be cached.

server {
 ...
 expires 7d;
 add_header Pragma "public";
 add_header Cache-Control "public";
 ...
}

In above case, all server requests supported by the configuration file will be cached.

3. Restart NGINX Server

Run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, then restart NGINX server by giving following command :

$ systemctl restart nginx #redhat/centos

Leave a Reply

Your email address will not be published. Required fields are marked *