![]()
A growing WordPress uploads directory can make backups slower, increase hosting storage costs, and place more delivery work on the web server. WordPress Media Offloading provides a practical way to move media objects to Amazon S3 and serve them through CloudFront while keeping WordPress attachment records and familiar media workflows in place. The result is a clear division of responsibility: WordPress manages attachment metadata, S3 stores the files, and CloudFront delivers them to visitors.
This guide follows a cautious deployment sequence: prepare WordPress, create private AWS resources, connect a compatible offloading integration, migrate existing files, then verify URLs and image sizes before considering any local-file cleanup. Start on staging and retain a tested backup throughout the work. Offloading changes where media files are stored and delivered; it does not replace a full-site backup or remove the need to protect your database, themes, plugins, and configuration.
Before You Begin
Use the prerequisite list above as a readiness check, then document how the site currently handles media before changing storage or delivery. This baseline makes it easier to spot configuration problems and gives you a practical rollback reference if a staging test fails.
- Record the uploads location: Note the configured uploads path and current public media URL pattern. If the site uses a custom uploads directory, confirm that your chosen integration supports it.
- Estimate the migration: Record the approximate number and total size of files in the uploads directory. Include generated image sizes, not just original uploads, when estimating transfer time and storage needs.
- Choose test attachments: Identify a few existing attachment IDs that cover different cases, such as a large photograph, a featured image, and an image displayed at a registered thumbnail size.
- Confirm the rollback route: Verify that the backup can restore both the database and local uploads, and decide who can reverse the deployment configuration if testing reveals broken media.
Keep the first implementation on staging, using the same plugin version and relevant configuration planned for production. A representative staging test should cover a new upload as well as files that already exist; success with one does not prove that the other workflow is configured correctly. Avoid changing the bucket, region, or object prefix midway through the test, because those choices determine where the integration writes and where CloudFront requests each object.
Offloading changes media storage and delivery, not the identity of WordPress attachments. Attachment IDs and editorial content generally remain in the WordPress database; the integration manages the relationship between those records, object keys, and delivered URLs. Do not manually replace media links in post content or delete local files as part of this preparation. First establish a repeatable test, a recoverable backup, and a clear production rollback procedure.
Step 1: Choose the Offloading Model and Prepare WordPress
Choose an integration that handles more than transferring an original image to a bucket. WordPress creates registered image sizes during upload, and themes may use those derivatives in featured images, galleries, and responsive srcset markup. A suitable offloading plugin should track the attachment metadata and object keys, copy the required files, and generate the correct delivery URLs without changing attachment IDs or requiring manual edits to post content.
Use a maintained option such as WP Offload Media, or another integration compatible with your site. Before installing it, verify that the specific plugin version supports your WordPress and PHP versions, Amazon S3, CloudFront URL delivery, and migration of existing media. Review its available storage and cleanup settings as well: the initial test should copy files to S3 and serve them through the CDN while retaining local copies.
Run the configuration on staging first, using the same plugin version and deployment method planned for production. Record the current URL for each representative attachment you will test. After setup, compare those results with the attachment URL, generated sizes, and front-end output produced by the integration. Keep configuration consistent across environments, and provide credentials through a hosting role or protected environment configuration rather than committing secrets to the repository.
Pro Tip
Avoid building a parallel custom upload handler or URL-rewriting filter for this workflow. The selected integration should own the relationship between WordPress attachments and their remote objects; competing code can produce inconsistent URLs or cause uploads and migrations to diverge. Treat local-file removal as a later, optional storage decision, not as a requirement for CDN delivery.
Did you know: You can set a WordPress Default Featured Image to ensure posts without a selected image still look polished and consistent, while saving time and strengthening your site’s visual identity.
Step 2: Create a Private S3 Bucket and Least-Privilege Access
Create a dedicated S3 bucket in the AWS region you selected for the site. Bucket names are globally unique, so choose a stable name that identifies the environment without including sensitive details. Decide on the object prefix now—for example, wp-content/uploads/—and keep it consistent in the WordPress integration. The bucket, region, and prefix together determine where files are stored; changing them after uploads can require a separate migration.
Keep the Bucket Private
Enable all S3 Block Public Access settings at both the account and bucket levels, and do not use public-read ACLs to make media load in a browser. CloudFront will be configured as the delivery path in the next step; it can retrieve objects from a private origin without making the bucket publicly accessible. Where available, use bucket-owner-enforced object ownership so access does not depend on individual object ACLs.
Enable encryption at rest, such as S3-managed encryption. If you choose a customer-managed KMS key, confirm that the identities involved in uploads and later CloudFront access are authorized to use it. Avoid adding a lifecycle expiration rule to the uploads prefix: expiration can permanently remove active media. Add transition or expiration rules only when you have a documented retention policy and have confirmed they cannot affect files WordPress still needs.
Limit WordPress AWS Access
Prefer a hosting-provider role or another short-lived role-based credential when your environment supports it. Otherwise, create a dedicated IAM identity for this site and store its credentials through protected environment configuration, not in a committed theme or plugin file. Do not grant administrator access or reuse a personal AWS credential.
Scope permissions to this bucket and the chosen object prefix. Bucket-level listing, typically needed for a plugin to discover or verify stored files, applies to the bucket resource; object operations such as upload, read, and delete apply to object resources under the prefix. Grant only the actions the selected integration actually requires. For example, omit delete permission if the workflow does not remove remote objects, and check the plugin requirements before restricting multipart-upload actions for large files. CloudFront access will use its own origin configuration rather than these WordPress credentials.
Before proceeding, record the exact bucket name, region, and prefix in your deployment notes. Use the same values in staging and production configuration, while keeping each environment’s credentials separate.

Step 3: Configure CloudFront with a Private S3 Origin
Create a CloudFront distribution that serves objects from the private S3 bucket. In the CloudFront console, add the bucket’s regional S3 REST endpoint as the origin—not the S3 static website endpoint—and create an Origin Access Control (OAC) for that origin. Configure OAC to sign requests to S3, then associate it with the distribution. This lets CloudFront retrieve objects without granting anonymous visitors direct bucket access.
Restrict Origin Access
After creating or updating the distribution, apply the bucket policy that allows the CloudFront service principal to read objects for this specific distribution. Use the distribution ARN as the policy condition, and limit the allowed resource to the media objects in the intended bucket or prefix. Keep S3 Block Public Access enabled and avoid public-read ACLs. The policy should authorize CloudFront—not make the bucket readable by everyone. AWS explains the supported setup in its guide to restricting access to an Amazon S3 origin.
Wait for the distribution status to show that deployment is complete before testing. Use the assigned CloudFront domain, such as d123example.cloudfront.net, as the initial delivery hostname. If you plan to use a custom hostname, add it as an alternate domain name, point its DNS record to the distribution, and attach a valid TLS certificate issued or imported in AWS Certificate Manager in us-east-1, the required region for CloudFront certificates.
Set Cache and Delivery Options
For ordinary media delivery, allow the required read methods, usually GET and HEAD, and avoid forwarding cookies or query strings unless the integration specifically needs them. Start with a managed cache policy appropriate for static assets, then confirm its TTL behavior against your media update workflow. Unique filenames or versioned URLs are the safest way to deliver changed files: the new URL naturally creates a new cache entry. If an object must be replaced at the same key, invalidate that specific CloudFront path after the upload; invalidation is a targeted operational fix, not a substitute for consistent URL versioning.

Step 4: Connect WordPress to S3 and CloudFront
On staging, install and activate the compatible offloading integration you selected. Connect it with the dedicated IAM identity or hosting role, then enter the S3 bucket name, AWS region, and the same object prefix chosen when you created the bucket. Set the delivery or CDN domain to your CloudFront hostname, such as d123example.cloudfront.net, or your configured custom hostname. Use the integration’s own settings for these values; do not add a separate URL-rewriting filter.
If your installed version supports the AS3CF_SETTINGS configuration constant, the following wp-config.php example reads deployment values from the PHP environment. Check that your version supports these setting keys before deploying it. Set the object prefix in the integration’s settings. Use a hosting role where supported; otherwise provide both AWS credential variables through protected environment configuration. This code never prints credentials.
if (!function_exists('pnet_media_env')) {
function pnet_media_env($name) {
$value = getenv($name);
return is_string($value) ? trim($value) : '';
}
}
$bucket = pnet_media_env('WP_MEDIA_S3_BUCKET');
$region = pnet_media_env('WP_MEDIA_S3_REGION');
$cdn_domain = pnet_media_env('WP_MEDIA_CDN_DOMAIN');
if ($bucket === '' || $region === '' || $cdn_domain === '') {
throw new RuntimeException('Media offload bucket, region, and CDN domain must be configured.');
}
$settings = array(
'provider' =>; 'aws',
'bucket' => $bucket,
'region' => $region,
'copy-to-s3' => true,
'serve-from-s3' => true,
'domain' => $cdn_domain,
);
$access_key = pnet_media_env('AWS_ACCESS_KEY_ID');
$secret_key = pnet_media_env('AWS_SECRET_ACCESS_KEY');
if (($access_key === '') !== ($secret_key === '')) {
throw new RuntimeException('Set both AWS credential variables, or use the configured hosting role.');
}
if ($access_key !== '') {
$settings['access-key-id'] = $access_key;
$settings['secret-access-key'] = $secret_key;
}
if (!defined('AS3CF_SETTINGS')) {
define('AS3CF_SETTINGS', serialize($settings));
}
Keep the integration’s option for deleting local files turned off. Upload a new test image through the WordPress Media Library, then confirm that its original and generated image sizes appear under the expected S3 prefix. View a page that uses the image and check that its rendered image URL uses the CloudFront hostname over HTTPS. Also test the media-library preview; a successful upload alone does not confirm that delivery URLs are correct.

Step 5: Migrate Existing Media and Validate Delivery
Before migrating, take a fresh backup of the database and local uploads, then run the integration’s supported existing-media migration on staging. If the tool offers batch size or concurrency controls, begin with a conservative batch and monitor server resources, AWS request limits, and migration logs. A resumable migration should let you continue after interruption without creating a second attachment or changing its metadata; confirm the plugin reports skipped or completed objects as expected before continuing.
Migrate in Controlled Batches
Compare the integration’s migration results with representative attachment records and the objects in the expected bucket prefix. Check originals, registered thumbnail sizes, and other generated sizes used by your theme. WordPress stores image-size information in attachment metadata, so use the integration to copy files and maintain that relationship; do not edit serialized database values or manually rewrite post content.
For a read-only inspection of an attachment, run this snippet in a temporary file loaded after WordPress, such as a temporary WP-CLI evaluation file. Replace 123 with a real attachment ID. It reports the attachment URL and image metadata without modifying the database or files; remove the temporary file after testing.
if (!function_exists('pnet_media_attachment_report')) {
function pnet_media_attachment_report($attachment_id) {
$attachment_id = absint($attachment_id);
if (!$attachment_id || get_post_type($attachment_id) !== 'attachment') {
return new WP_Error('invalid_attachment', 'The supplied ID is not a media attachment.');
}
$metadata = wp_get_attachment_metadata($attachment_id);
$sizes = array();
if (is_array($metadata) && !empty($metadata['sizes'])) {
foreach ($metadata['sizes'] as $name => $size) {
$sizes[$name] = array(
'file' => isset($size['file']) ? $size['file'] : '',
'width' => isset($size['width']) ? (int) $size['width'] : 0,
'height' => isset($size['height']) ? (int) $size['height'] : 0,
);
}
}
return array(
'attachment_id' => $attachment_id,
'url' => wp_get_attachment_url($attachment_id),
'metadata_file' => is_array($metadata) && isset($metadata['file']) ? $metadata['file'] : '',
'width' => is_array($metadata) && isset($metadata['width']) ? (int) $metadata['width'] : 0,
'height' => is_array($metadata) && isset($metadata['height']) ? (int) $metadata['height'] : 0,
'sizes' => $sizes,
);
}
}
$report = pnet_media_attachment_report(123);
if (is_wp_error($report)) {
error_log($report->get_error_message());
} else {
error_log(wp_json_encode($report, JSON_UNESCAPED_SLASHES));
}
Check CDN Delivery Before Cleanup
Review pages that exercise different media paths: featured images, galleries, responsive srcset output, and media-library previews. Confirm the URLs use the intended HTTPS CloudFront hostname and that each requested derivative exists in S3. For sample URLs, check for an HTTP success response and an appropriate Content-Type, such as image/jpeg or image/webp. A CloudFront cache miss can still be a successful response: it means the edge fetched the object from the origin. A 403 instead points to access, distribution, or object-key configuration that needs investigation.
Backup Required
You might also like:
Common Errors
When a media URL fails, identify whether the problem is in WordPress, the CloudFront distribution, or the S3 origin before changing permissions. Check the requested URL and object key first; making the bucket public can hide a configuration mistake while weakening access controls.
| Symptom | Likely cause | Safe fix |
|---|---|---|
| 403 AccessDenied | CloudFront is not authorized to read the object, OAC is missing or misconfigured, or the requested key does not exist. | Compare the URL path with the exact S3 object key. Verify that OAC is attached to the correct S3 origin and that the bucket policy allows the intended distribution to read the required objects. Wait for the distribution update to deploy. Do not enable public access. |
| 404 Not Found | The bucket, region, case-sensitive path, or object prefix differs from the integration settings; a derivative may not have been migrated. | Compare the requested key with the S3 console object path. Confirm the prefix and region, then use the integration’s migration tool to copy missing image sizes. |
| Pages still use the origin URL | The CDN hostname is absent or incorrect in plugin settings, a cached page is stale, or another rewrite plugin conflicts. | Check the hostname setting and ensure the offloading integration owns attachment URL handling. Clear the relevant page cache and investigate conflicting URL-rewrite rules before changing code. |
| Mixed-content or TLS warnings | Media URLs use HTTP, or a custom hostname has an invalid certificate or DNS record. | Configure the integration to use the HTTPS CloudFront or custom hostname. Verify the certificate covers that hostname and DNS points to the distribution. |
| Only original images load | Generated sizes are missing from S3 or attachment metadata does not match the migrated files. | Inspect the attachment metadata and expected object keys, then rerun the supported migration for missing derivatives. Do not manually edit serialized database values. |
| Old image remains visible | The browser, page cache, or CloudFront has a cached response. | Check the object directly and clear the relevant browser or page cache. If the same key was replaced, invalidate only the affected CloudFront path; prefer a new versioned filename for future changes. |
| Uploads fail after credential changes | The active role or access key is unavailable, or lacks required write permissions for the bucket prefix. | Verify the production environment uses the intended role or credential pair and that its permissions cover the integration’s required upload operations. Never print secrets in logs. |
Change one setting at a time and retest the same image URL so the result points to a specific correction. For persistent failures, compare the integration’s reported bucket, region, prefix, and CDN hostname with the deployed AWS configuration, then review logs without exposing credentials. Keep local files and the backup intact until delivery is working across originals and derivatives.
You might also like:
Conclusion
A reliable rollout starts with a tested backup and a staging trial, then moves through a deliberate sequence: create a private S3 bucket, restrict WordPress access to the required bucket operations, and configure CloudFront to read from S3 through Origin Access Control. Connect those resources with a compatible WordPress integration, keeping local files in place while you test. This setup lets WordPress continue managing attachment records and metadata while S3 stores media objects and CloudFront delivers them to visitors.
Migration is not complete just because original uploads appear in the bucket. Confirm that generated image sizes are present, attachment URLs resolve through the intended HTTPS CloudFront hostname, and representative pages display correctly—including responsive images, galleries, featured images, and media-library previews. If a check fails, keep the local files and use the integration’s supported migration and troubleshooting tools rather than making the bucket public or introducing a competing URL rewrite.
Once delivery is verified and you have confirmed a recovery path, decide whether retaining local copies still suits your backup and storage plan. Removing them is optional; it is not necessary for CDN delivery. Keep a restorable copy, document the AWS and WordPress configuration, and apply any cleanup only after the full migration has passed its checks. With private origin access, least-privilege credentials, and careful validation, WordPress Media Offloading can reduce the media burden on your web server without sacrificing a recoverable deployment.