X

Nginx Browser Caching

You can use Nginx to Set cache expiration times  to leverage browser caching for the user requesting specific file types. This will cause the browser to retain the downloaded image until the length of the expires header. This will cause faster page time loads on each subsequent request performed by the end user.

Prerequisites:

You will need to have Nginx already installed. If you do not please see How To Install Nginx From Source On CentOS

How To Check Current Nginx Browser Cache Behavior

Check headers on a existing image:

 $ curl -Is http://domain.com/test.png

HTTP/1.1 200 OK
Server: nginx/1.11.13
Date: Thu, 08 Jun 2017 01:26:19 GMT
Content-Type: image/png
Content-Length: 6983
Last-Modified: Fri, 28 Apr 2017 02:21:20 GMT
Connection: keep-alive
ETag: "5902a720-1b47"
Expires: Thu, 15 Jun 2017 01:26:19 GMT
Cache-Control: max-age=604800
Accept-Ranges: bytes

If you look at the request, It is missing  a Expires header. This is what needs to be in place to tell the browser to not check the file again until the cache time has expired.

Nginx Browser Cache Configuration

To implement this, you will need to edit your Nginx server configuration

nano /etc/nginx/nginx.conf

Inside the server{} you will want to place the file types you would like to cache and their respective times:

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

The first block says for the following file types .png, .jpg, .jpeg, .gif, .ico, and .otf you want to cache them for a period of 1 year. The second location indicates you want to cache .js and .css files for a period of 7 days.  You can add other file types or adjust the time as you see first based on the needs of your site. Once that has been completed, go ahead and save the file.

Once that has been completed you will want restart Nginx to save the new configuration:

service nginx restart

You can then go ahead and check the same image as you did before adding the headers

$ curl -Is http://domain.com/test.png

HTTP/1.1 200 OK
Date: Thu, 08 Jun 2017 01:25:57 GMT
Content-Type: image/png
Content-Length: 6983
Connection: keep-alive
Last-Modified: Fri, 28 Apr 2017 02:21:20 GMT
ETag: "5902a720-1b47"
Expires: Fri, 25 May 2018 23:17:30 GMT
Cache-Control: max-age=31536000

You now see the Expires header and the  time which should correspond with the length of the header you set on the file type.  This will improve page speed for end users when they make multiple similar requests and it will also reduce overall server consumption per page request as well.

LinuxAdmin.io
0 0 votes
Article Rating
LinuxAdmin.io:
Related Post