checkm
checkm

Reputation: 119

How to manually offload wordpress media directory

A blog owner wants to free disk space in his shared hosting. In order to do that, he thinks to offload old media files to another external webserver (...instead of upgrading the hosting plan...). Note that he doesn't need to reuse those media files from the wordpress media library anymore. So, as long as the old blog posts keep showing the right pictures in public thumbnails and article pages he's satisfied. Also, he doesn't want to rely on external cloud services such as Amazon S3, Google Cloud Storage or similar (otherwise I could easily do that with WP Offload plugins!).

So the idea is to:

  1. configure the webserver on a third level domain, like old.myblog.ext
  2. move all wp-content/uploads/[old-years]/ folders to old.myblog.ext
  3. from MySQL, replace all occurences for https://myblog.ext/wp-content/uploads/[old-years]/ with https://old.myblog.ext/wp-content/uploads/[old-years]/ (this is supposed to change all URLs for <img src="..."> tag in the posts source code)
  4. create a redirection rule for 404 errors from myblog.ext to old.myblog.ext (this is supposed to preserve search engines ranking)

This may be not a clean solution, but would it work? May step n. 3 cause any issue by accidentally affecting or breaking other website parts? Should I limit the query to wp_posts or extend it to other tables?

update wp_posts set post_content =
replace(post_content,'https://myblog.ext/wp-content/uploads/[old-years]/','https://old.myblog.ext/wp-content/uploads/[old-years]/');

What about featured images and thumbnails? Should GUID be included in the replace query?

Upvotes: 0

Views: 294

Answers (1)

checkm
checkm

Reputation: 119

I tried the procedure mentioned above, and it worked perfectly. The only images that are not being redirected are the featured images and thumbnails. The reason is that these images are not contained in the wp_posts table, like the content of individual articles, but rather in the wp_postmeta table, with meta_key = _wp_attached_file. However, this aspect is not manageable with a SQL search and replace query because the paths contained in this table are relative. The absolute path is 'constructed' by WordPress. For this reason, I managed the featured images and thumbnails with the following filter in functions.php:

function outsource_featured_images($image, $attachment_id, $size, $icon) {
    $image[0] = str_replace("https://myblog.ext/wp-content/uploads/[old-year]/", "https://old.myblog.ext/wp-content/uploads/[old-year]/", $image[0]);

    return $image;
}

add_filter('wp_get_attachment_image_src', 'outsource_featured_images', 10, 4);

Finally, before freeing disk space on the main hosting, I had to create the redirect rule in .htaccess:

RedirectMatch 301 ^/wp-content/uploads/[year]/(.*)$ https://old.myblog.ext/wp-content/uploads/[year]/$1

Upvotes: 0

Related Questions