Nginx Client Caching

nginx(8) has a simplified API to managing the headers that affect client-side caching of resources.


Unit Measurements

In nginx(8) configuration files, time is measured in...

In that case that a plain integer is provided (i.e. no suffix), it is treated as a measurement in seconds.

Units can be combined as long as they are in order from greatest to least significance. A space between units is optional. For example, 2h30m and 2h 30m may be more readable than 150m.


Enabling

To cause a client device to cache all web resources for the next 30 days, try the following:

location / {
  expires 30d;
}

The expires directive sets the Expires and Cache-Control headers. The expiry will happen at current time plus the parameter passed on the expires directive. This can either be an integer (e.g. `expires

This is more effective when applied to a subset of resources, such as images or CSS stylesheets. Simply adjust the location block that the expires directive is used in.


Disabling

Consider one of these two options:

location / {
  expires off;
}

The off keyword disables adding Expires and Cache-Control headers. This is not necessarily the same as disabling client-side caching though.

location / {
  expires -1;
}

Passing a negative value sets the expiry to a past time, so that all resources will always be considered expired. The Cache-Control header will also be automatically set to Cache-Control: no-cache.


Tips

Take into account how the Cache-Control header will interact with compression.


See also

Module ngx_http_headers_module documentation


CategoryRicottone

Nginx/ClientCaching (last edited 2023-08-06 18:36:16 by DominicRicottone)