How To Specify Cache Control In WordPress?

If you are using Nginx or Varnish as reverse proxy to cache your WordPress website, you should specify cache control from functions.php so that your reverse proxy knows which page should be cached (for how long) and which page should not be cached at all. If you don’t want to touch functions.php, then you should specify cache periods in your reverse proxy configuration files but this might be a little tricky. We believe it’s easier and more flexible to do this in WordPress rather than playing with Nginx or Varnish configuration files.

Respect Pragma Header Controls

In both Nginx and Varnish configurations, there are parameters that tells the caching mechanisms to respect what comes from header of the proxied response. If these parameters are not included in our configuration, then even if we specify cache control parameters in our headers, our reverse proxy may not care and use its own cache rules. For example, if we want to send Pragma: no-cache from WordPress headers so that a page is not cached at all, then we should definitely have the following line in our virtual.conf:

In Varnish, if you see the following line in your vcl configuration, then you should remove it because it simply ignores cache control:

How To Send Headers From WordPress ?

In functions.php, you can create a function that can specify cache-control based on content type. In the following function, basically we specify different cache durations so that our Nginx reverse proxy caches content accordingly:

Basically, we assume that our front page, category and tag pages are changing frequently and therefore, we set max-age to 45 seconds. Our nginx will cache these pages for only 45 seconds. If this is a post, which is more than 14 days old, then we can cache it for a longer period since it will be unlikely to be modified.

You should always keep in mind that a page has to be requested at least once for a reverse proxy to cache it.