Skip to content

Commit

Permalink
Redirect local media URLs to cdn URLs. (#796)
Browse files Browse the repository at this point in the history
* Redirect local media URLs to cdn URLs.

* Update amazon-s3-and-cloudfront.php
  • Loading branch information
EarthlingDavey authored Nov 25, 2024
1 parent c13cb64 commit c878164
Showing 1 changed file with 54 additions and 5 deletions.
59 changes: 54 additions & 5 deletions public/app/themes/clarity/inc/amazon-s3-and-cloudfront.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,67 @@ class AmazonS3AndCloudFrontTweaks
public function __construct()
{
// Increase limits from 50 to 5000.
add_filter( 'as3cf_update_replace_provider_urls_batch_size', fn() => 5000);
add_filter( 'as3cf_update_filter_post_excerpt_batch_size', fn() => 5000);
add_filter('as3cf_update_replace_provider_urls_batch_size', fn() => 5000);
add_filter('as3cf_update_filter_post_excerpt_batch_size', fn() => 5000);

// Increase limits from 500 to 3500, duration is about 45 seconds.
add_filter( 'as3cf_update_fix_broken_item_extra_data_batch_size', fn() => 3500);
add_filter('as3cf_update_fix_broken_item_extra_data_batch_size', fn() => 3500);

// Increase limit from 50 to 750.
add_filter( 'as3cf_update_as3cf_items_table_batch_size', fn() => 750);
add_filter('as3cf_update_as3cf_items_table_batch_size', fn() => 750);
// 750 items take ~20 secs, so decrease interval from 2 to 1 minute.
add_filter( 'as3cf_update_as3cf_items_table_interval', fn() => 1);
add_filter('as3cf_update_as3cf_items_table_interval', fn() => 1);

// Redirect legacy URLs to cdn URLs.
add_action('template_redirect', [$this, 'maybeRedirect404s']);
}

/**
* Redirect local media URLs to cdn URLs.
*
* Some content has links to documents and media that have the path `/wp-content/uploads/`.
* These paths are redirected to `/app/uploads/` by Bedrock.
*
* A further redirect is required to redirect `/app/uploads/` to the CDN URL.
*
* @return void
*/

public function maybeRedirect404s(): void
{
if (!is_404()) {
return;
}

// Check if the request is for a local upload URL.
if (!str_starts_with($_SERVER['REQUEST_URI'], '/app/uploads/')) {
return;
}

// Replace '/app/uploads/' with '/media/'.
$media_uri = str_replace('/app/uploads/', '/media/', $_SERVER['REQUEST_URI']);

// Make it an absolute URL for `attachment_url_to_postid`.
$absolute_url = get_home_url(null, $media_uri);

// Get the attachment id from the url.
$attachment_id = attachment_url_to_postid($absolute_url);

if (!$attachment_id) {
return;
}

// Get the url from the attachment id.
$cdn_url = wp_get_attachment_url($attachment_id);

if (!$cdn_url) {
return;
}

// Redirect to the CDN URL.
wp_redirect($cdn_url, 301);
exit;
}
}

new AmazonS3AndCloudFrontTweaks();

0 comments on commit c878164

Please sign in to comment.