That seems like a nice way to do it, thank you very much for sharing. But I guess I do need some kind of JSON file which outputs all the different redirect urls right? Like so:
[
{
from: ‘url’,
to: ‘new-url’,
}
]
I am still not sure how to write the actual code for the KV; can you show me a more complete example, or perhaps send me some tutorials where I can learn more in depth?
I managed to write my own script, despite low amount of effort from the “community”. I wanted to share here, in case somebody is looking for the same solution.
Inside your “handleEvent” function, add this piece of code:
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* Check for 301 redirects
*/
const redirect = await REDIRECTS.get(url.pathname).then((redirectJson) => {
if(redirectJson) {
let redirect = JSON.parse(redirectJson);
url.pathname = redirect.path;
// return { url: url.href, type: redirect.type.replace };
return { url: url.href, type: 301 };
}
});
if(redirect) {
return Response.redirect(redirect.url, redirect.type);
}
You have to have created a KV, (I called mine ‘REDIRECTS’) and then check the pathname of the incoming request. You’ll then search the KV for any key named the current path. If a key is found, a JSON string will be returned that you’ll need to parse (JSON.parse) and then extract the information from there.
Here’s an example of how the data looks:
(the key is the name of the path (what’s coming after the domain name) and the data is a JSON object containing the new path as well as what type of redirect you want).
I then made a wordpress CLI script to import all the redirects into the KV.
/**
* Sync redirects to Cloudflare KV
*
* Usage: `wp test`
*/
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'sync-redirects', 'sync_redirects_to_kv' );
}
function sync_redirects_to_kv() {
$redirects = get_option('wpseo-premium-redirects-base');
$kvBody = [];
foreach($redirects as $redirect) {
$kvBody[] = [
'key' => '/' . $redirect['origin'],
'value' => json_encode([
'path' => '/' . $redirect['url'],
'type' => $redirect['type'] // be careful, as Cloudflare only supports 3-399 redirects. Yoast will have some 410 redirects that CloudFlare doesn't support. You could hardcode 301 here instead.
])
];
}
$account_id = '';
$namespace_id = '';
$auth_key = '';
$auth_email = '';
$ch = curl_init('https://api.cloudflare.com/client/v4/accounts/' . $account_id . '/storage/kv/namespaces/' . $namespace_id . '/bulk');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($kvBody));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Auth-Key: ' . $auth_key,
'X-Auth-Email: ' . $auth_email,
'Content-Type: application/json'
]);
$response = curl_exec($ch);
exit(var_dump($response));
}