Configure Browser Caching in Nginx

The faster a website loads, the more likely a visitor is to stay. One of the important steps to take is to configure browser caching. This is to tell the browser that files downloaded once can be reused from local copies instead of requesting the server for them again and again. To do this, new HTTP response headers telling the browser how to behave must be introduced.

sudo vim /etc/nginx/sites-available/default
# Expires map
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

server {
    # ...
    expires $expires;
}

Inside the server block, the expires directive (a part of the headers module) sets the caching control headers. It uses the value from the $expires variable set in the map. This way, the resulting headers will be different depending on the file type.

Finally, we need to restart Nginx:

sudo systemctl restart nginx

Reference