~configuring nginx caching

January 27, 2017

to optimize server performance for faster access, sysadmins often add caching settings. typically, nginx is combined with varnish as a proxy caching solution. however, in my experience, configuring nginx caching alone is often sufficient since nginx can also act as a caching server similar to varnish. perhaps we’ll explore the combination of nginx and varnish, as well as nginx installation on ubuntu, in a future post.

configuring nginx caching

setting up caching in nginx is straightforward. start by editing your nginx server block configuration file. if you’re not using server blocks, modify the default configuration file instead:

sudo nano /etc/nginx/sites-available/domain.com

add the following caching rules before the closing curly brace (}):

# rss and atom feeds
location ~* \.(?:rss|atom)$ {
  expires 1h;
  add_header cache-control "public";
}

# media files
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
  expires 30d;
  access_log off;
  add_header cache-control "public";
}

# css and javascript
location ~* \.(?:css|js)$ {
  expires 1y;
  access_log off;
  add_header cache-control "public";
}

explanation of caching rules

  • rss and atom feeds: cache these files for one hour (1h).
  • media files: cache images, videos, and similar files for 30 days (30d).
  • css and javascript: cache these files for one year (1y).

the cache-control header is set to public to allow caching by all devices.

restart nginx

once the configuration changes are made, restart the nginx service to apply the updates:

sudo service nginx restart

with these settings, your server will deliver cached content more efficiently, improving load times and reducing server load.