Shows the configuration to implement an efficient cache policy on the Nginx Web Server to leverage browser caching.

Enable Leverage Browser Caching on Nginx
Enable Leverage Browser Caching on Nginx
October 08, 2019

In the previous tutorial - Enable Gzip Compression On Nginx, I have explained to speed up the website by enabling gzip compression. We can further speed up the websites by enabling efficient cache policies to leverage browser caching of websites and applications hosted on the Nginx WebServer. This tutorial provides the options to configure caching by updating the location context.

Leverage Browser Caching

We can enable client-side caching by updating the http or server block. I have updated the server block for the demonstration as shown below.

# Leverage Browser Caching
sudo nano /etc/nginx/sites-available/example.com

server {
listen 80;
server_name example.com;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

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

location ~* \.(pdf)$ {
expires 30d;
}
}

# Save and exit the editor

# Check configurations
sudo nginx -t

# Output
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

# Restart Nginx
sudo systemctl restart nginx

In this way, we are instructing the browser to maintain a local cache of the static assets with extensions jpg, jpeg, png, gif, ico, css, and js for 365 days. We are also telling browsers to cache the pdfs for 30 days using a separate location block.

We can also specify the duration in hours or minutes as shown below.

# Expires in 10 hours
expires 10h;


# Expires in 30 minutes
expires 30m;

Below mentioned are the header configurations that can be used with the response sent by the server.

# Headers - Pragma and Cache-Control

add_header Pragma "public";
add_header Cache-Control "public";

# Example

location ~* \.(pdf)$ {
expires 30d;
add_header Pragma "public";
add_header Cache-Control "public";
}

It might be required to disable caching for some sections of your website. It can be done as shown below.

# Disable browser caching - never cache

server {
...
...

location /private {
add_header Pragma "no-cache";
add_header Cache-Control "private, max-age=0, no-cache, no-store";
}

...
...
}

We can also commit to the browsers about certain static assets that are not supposed to change by any means. It can be done as shown below.

# Always cache

server {
...
...

location /static {
add_header Pragma "cache";
add_header Cache-Control "public";
}

...
...
}

Summary

We have enabled efficient cache policy to leverage browser caching on Nginx. This will avoid the server from serving the same static assets on multiple requests, hence speeding up the sites and reducing the network payload.

Write a Comment

Click on the captcha image to get new code.
Discussion Forum by DISQUS