Modify the maximum cache age
For most responses with an HTTP Status Code of 200
, the default cache-control
response header value set by VIP’s page cache is max-age=300
. This can be set to a custom value on WordPress and Node.js applications.
Routes for site endpoints that rarely change should be set to a higher max-age
value, which can improve the cache hit rate.
There is no upper limit to the value set for max-age
, but increasing this value is only beneficial within a limited range. By default, cached page content is evicted from the cache according to the max-age
TTL and the GRACE
response, which is set to 12 hours for content that is unable to be refreshed.
The page cache also relies on a Least Recently Used (LRU) strategy which will apply if the page cache is low in memory. As a result, setting max-age
to a value beyond a certain range (e.g. > 24 hours) can result in content that is requested less often to occupy valuable space in the page cache, which can lead to more frequent page cache evictions.
Caution
Do not set max-age
to less than 1 minute for heavily trafficked resource types.
Caching for static assets of WordPress and Node.js environments has a different set of default behaviors.
In this WordPress code example, max-age
is set to a custom value for feeds. Note that the example includes an is_user_logged_in()
check. This ensures that the cache Time To Live (TTL) headers are not set for logged-in users, as this would trigger browser caching for them.
add_action( 'wp', 'my_cache_maxage' );
/**
* Hooks the wp action to insert some cache control
* max-age headers.
*
* @param Object wp The WP object, passed by reference
* @return void
*/
function my_cache_maxage( $wp ) {
if ( is_feed() ) {
// Set the max age for feeds to 10 minutes.
if ( ! is_user_logged_in() ) {
header( 'Cache-Control: max-age=' . ( 10 * MINUTE_IN_SECONDS ) );
}
}
}
In this Node.js code example, max-age
is set to a custom value for an Express.js route.
const express = require( 'express' );
const app = express();
app.get( '/', function ( req, res ) {
res
.set( 'cache-control', 'max-age=3600' )
.send( 'This response will be cached for 1 hour (3600 seconds)' );
});
Last updated: March 12, 2024