After I published a recent article where I showed how to mitigate an accidental DDoS after enabling ActivityPub for WordPress with the Surge plugin, I found an optimization for improved cache handling. Out of the box, there’s a problem with the default configuration since Surge ignores the Accept header.

This Accept header is a value usually every request is sending to your server. By accessing this page through the browser for instance, the value for this Accept header is something like text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8. It tells the server that the client (i.e. the browser in this case) generally accepts HTML, XHTML and XML as answer.

When working with ActivityPub, the Accept header value usually looks like this: application/activity+json to tell the server it wants to get a JSON in the ActivityPub variant.

If you now use Surge in its default configuration, this Accept header is basically ignored. That means, if I access a post via browser, the HTML is cached. If afterwards someone accesses the post, but wants to access the ActivityPub variant, the cached HTML is returned instead of the desired JSON.

Luckily, Dominik Schilling found a smart solution for this to store different cache versions according to the Accept header. The code looks like this:

<?php
// Content negotiation.
$representation = 'html'; // Or 'generic'.
if ( isset( $_SERVER['HTTP_ACCEPT'] ) ) {
	$accept = strtolower( $_SERVER['HTTP_ACCEPT'] );

	if ( str_contains( $accept, 'text/html' ) ) {
		$representation = 'html';
	} elseif (
		str_contains( $accept, 'application/json' ) ||
		str_contains( $accept, 'application/activity+json' ) ||
		str_contains( $accept, 'application/ld+json' )
	) {
		$representation = 'json';
	}
}
$config['variants']['representation'] = $representation;
unset( $accept, $representation );

return $config;
Code language: PHP (php)

Place it in a file cache-config.php in the root directory of your WordPress instance and load it by adding the following value to your wp-config.php:

define( 'WP_CACHE_CONFIG', __DIR__ . '/cache-config.php' );Code language: PHP (php)

After that, the file is directly loaded and active and everything should went smoothly. πŸ™‚

4 comments

Likes

Reposts

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn more about webmentions)