Mastering Nginx

(Ron) #1
Chapter 7

[ 165 ]

Caching in the filesystem


Suppose your application writes prerendered pages as files. You know how long


each file should be valid. You can configure NGINX to deliver certain headers with
each file that instruct the client, and any proxy in between, how long the file should


be cached. In this way, you have enabled a local cache for your users without having
to change a single line of code.


You can do this by setting the Expires and Cache-Control headers. These are
standard HTTP headers understood by clients and HTTP proxies alike. No change


is required in your application; you merely need to set these headers in the NGINX
configuration block for the corresponding locations. NGINX makes it convenient by


providing the expires and add_header directives.


Table: Header modifying directives

Directive Explanation
add_header Adds fields to a header present in the
responses with HTTP codes 200, 204, 206,
301, 302, 303, 304, or 307.
expires Adds or modifies the Expires and
Cache-Control headers. The parameters
can be an optional modified parameter,
followed by time, or one of epoch,
max, or off. If time alone is present,
the Expires header will be set to the
current time plus the time specified in
the time parameter. Cache-Control
will be set to max-age=t, where t is the
time specified as an argument, in seconds.
If the modified parameter precedes a
time value, the Expires header is set to
the file's modification time plus the time
specified in the time parameter. If the
time contains an @, the time specified
will be interpreted as the time of day;
for example, @12h is 12 noon. epoch is
defined to be the exact date and time Thu,
01 Jan 1970 00:00:01 GMT. max
sets Expires to Thu, 31 Dec 2037
23:55:55 GMT and Cache-Control
to 10 years. Any negative time will set
Cache-Control to no-cache.
Free download pdf