RA

ritu_aggrawal

Site reliability engineer at Uber Updated Feb. 2, 2020, 3:24 p.m. ⋅ 154 views

How to Implement Browser side Caching of static files on Nginx with header


Static files are almost in every website and the faster they load the better is user experience. Static files contain images, css fies, javascript files etc.

HTTP requests to these static files should not hit the web servers, they should be handled by HTTP request handlers, like Ngnix.

Usually, static files are not modified very frequently and its a good idea to make user's browser store them, so our server doesn't need to server for every click.

This will dramatically reduce network bandwidth usage and speed up the website loading.

All browsers, allows us to give them instruction to store some files. In order to implement that, we need to set the header with HTTP response we send from server.

Ngnix is the most common HTTP request handler that is used.

In this article, i'll tell you how to set HTTP header for static files to implement browser side caching of static files.

 

Prerequisites

 

I'm assuming you have hosted your server on any linux server and you have access to its command window, from where you can modify Ngnix files.

 

Implementation

Go to  /etc/nginx/sites-available/

Then open defualt file using vim or if you have a seperate file for your website replace that with defualt

sudo vim default

 

Now add follwoing lines inside server configuration

server {


....

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}

....

}

 

Here, we are setting cache of ico, css, js, gif, jpe, jpeg and png files to 30 days. You ca play around with to set cache as per your requirements.

Once after doing that you need restart Ngnix. 

Finally, you can verfy HTTP header of resopnse of any files in given type.

 



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details