Optimize Surge configuration for ActivityPub
Published: β 4 Comments
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. π
@epiphyt_en If you like that drop-in youβll love https://github.com/Automattic/wordpress-activitypub/pull/1648 π
Nearly immediately outdated my post. π
@obenland
Great π . Will you Release Version 5.9.0 of #ActvityPup tomorrow?
CC @epiphyt_en
@NickBohle @epiphyt_en Iβd expect it to ship some time next week