Move Images to S3
If your WordPress website contains a large number of images, eg, you’re a photographer, you may want to move those images to cheaper storage like Amazon’s S3.
If you already have a large number of images on your server you may find a plugin like https://github.com/humanmade/S3-Uploads handy to move them to S3 in bulk.
Use their documentation to copy the uploads directory to S3. Because they seem to have a bug in their software, it doesn’t do URL replacements for images in the copy (ie, it’s only currently working on featured posts) for existing posts. So, we’ll change the URL for existing posts as per the below.
Change URL in WordPress Itself
Next, we’re going to “hard” rewrite the image URLs in the database. If you create a page or post and add an image into it you’ll see two (or more) entries in wp_posts. One is for the post itself, and another for the image (one for each image).
In WP 5 and up the post row as well as in the image row in the database.
What we’re going to do after moving our entire uploads directory to S3 is we’re going to change the link. For instance, if our original image was:
and our S3 image is located at:
then we want to run a script to do a replacement directly in the database for that.
For that we’ll use WP-CLI search/replace functions (yes, on the command line again).
wp search-replace "http://example.com/wp-content/uploads" "https://s3.sa-east-1.amazonaws.com/example/uploads" --all-tables
This will search for http://example.com/wp-content/uploads in every table and replace it with https://s3.sa-east-1.amazonaws.com/example/uploads.
We can now delete our uploads folder (after taking a backup).
Now that we’ve moved our existing images and changed the database to point to those image we can enabled the S3-Uploads plugin so that all new images are sent to S3.