Mastering Nginx

(Ron) #1

NGINX for the Developer


[ 160 ]

Caching was introduced in Chapter 5, Reverse Proxy Advanced Topics. In this section,


we will take an in-depth view of integrating NGINX's caching mechanisms into a web
application. Your web application may already cache to a certain extent. Perhaps it


writes pre-rendered pages into a database so that an expensive rendering task does
not have to be repeated at each page view. Or, even better, your application may write


prerendered pages into the filesystem, so that they can simply be served by NGINX's


stellar static file performance. No matter the caching mechanism your application
already has (even if it has none), NGINX offers a way to integrate it into the server.


No application caching


When your application does no caching at all, NGINX can still help speed up your


users' response times. Both the proxy and the fastcgi modules are able to make
use of this caching feature. You will therefore either be using the proxycache*


or the fastcgicache* directives to configure caching for your application.


The proxycache directives were described in the Caching section in Chapter 5,
Reverse Proxy Advanced Topics; the fastcgicache
directives summarized


in Chapter 6, The NGINX HTTP Server.


Here we will describe how to extend your application to instruct NGINX how to


cache individual pages. This is done by using headers sent to NGINX. You can use
either the standard Expires and Cache-Control headers or the special X-Accel-


Expires header, which NGINX interprets for caching and does not pass on to the
client. This header allows the application to completely control how long NGINX


caches a file. This makes it very easy to expire normally long-lived objects.


Let's say that you have a news application that's suffering from slow page load


times. This can happen for different reasons, but after analysis, you have determined
that each page is rendered in real time from the content stored in a database. When


a user visits the site, this causes a new database connection to be opened, multiple


SQL queries to be made, and the result to be parsed, before a fully-rendered page
can be delivered to that user. Due to multiple connections in the application's


backend system, the architecture cannot easily be restructured to make use of
a more reasonable rendering strategy.


Given these restrictions, you decide on the following caching strategy:



  • The front page is to be cached for 1 minute, as this contains links to articles
    and the list is frequently updated

  • Each article will be cached for 1 day because once written they don't change,
    but we don't want the cache to be filled with older entries that need to be
    removed due to lack of space

Free download pdf