Setting up Nginx, a leading web server, to cache content instead of using a dedicated application like Varnish is increasingly being adopted by many webmeisters.
But most of the online tutorials that show how to configure Nginx to cache content were copied from other sources that were also copies from other sources. And in virtually all the examples I’ve seen, there’s very little or no explanation of what each directive and parameter means and does.
That’s a recipe for setting up a system that does not cache or caches everything, even those that should not be cached. I think I’m guilty of the former, because this website does not appear to be caching, even though caching is configured.
So it’s refreshing to come across a blog post that explains all the basics clearly, including a few parameters that were introduced in more recent editions of Nginx. That the blog post is from the proverbial horse’s mouth makes it that much more authentic.
So here’s an excerpt from the tutorial:
Last year I took on the task of performance tuning a website that was loading slowly. One of the first things I noticed was that it took over 1 second to generate the main home page. After some debugging, I discovered that because the page was marked as not cacheable, it was being dynamically generated in response to each request. The page itself was not changing very often and was not personalized, so this was not necessary. As an experiment, I marked the home page to be cached for 5 seconds, and just doing that resulted in noticeable improvement. The time to first byte went down to a few milliseconds and the page loaded visibly faster.
It’s not only large-scale content delivery networks (CDNs) that can benefit from caching – caching can boost the performance of the load balancers, reverse proxies, and web servers sitting in front of your application servers. As the above example shows, caching content results in more efficient usage of application servers because they don’t have to do the work of generating pages from scratch each time.
A web cache can be used to improve reliability as well. Rather than return an error to the user if the origin servers are down or busy, NGINX can be configured to deliver the stale content it already has in its cache. This means sites can remain partially or even fully functional in the case of a failure of the application servers or database.
You may read the complete article at A Guide to Caching with NGINX.