Skip to content

Instantly share code, notes, and snippets.

@mwender
Last active December 23, 2024 19:42
Show Gist options
  • Save mwender/46fba9f06358dde3e85c11b34c17f01f to your computer and use it in GitHub Desktop.
Save mwender/46fba9f06358dde3e85c11b34c17f01f to your computer and use it in GitHub Desktop.
[WordPress NGINX CDN Redirect Rules] Redirects not found requests in WP uploads to a CDN URL you define #nginx #wordpress

NGINX Configuration for Redirecting WordPress Uploads to a Production CDN

This configuration is designed to redirect all requests to the WordPress uploads directory (/wp-content/uploads/) to a specified production Content Delivery Network (CDN). This setup helps offload static media assets to the CDN, reducing load on the main server and improving load times.

Configuration Details:

  • The $production variable defines the CDN URL where the assets are located.
  • Requests for resources within /wp-content/uploads/ are first checked locally. If the file is not found, the request is rewritten to the CDN location.

Directives:

  • set $production: Sets the CDN URL, which can be modified as needed.
  • location @prod_uploads: Defines a named location that rewrites URLs to the CDN for resources in the /wp-content/uploads/ directory.
  • location ~ "^/wp-content/uploads/(.*)$": Matches requests for the /wp-content/uploads/ directory and attempts to serve files locally. If files are not found, it forwards the request to @prod_uploads, triggering the CDN rewrite.

Usage:

Place this configuration within an appropriate server block in your NGINX configuration to enable fallback loading from the CDN for WordPress media. Ensure the $production variable points to the correct CDN path for your assets.

Appendix 1 - SpinupWP NGINX

On SpinupWP, place this config here:

/etc/nginx/sites-available/{$site}/server/

Appendix 2 - s3cmd Setup for DigitalOcean Spaces

See Setting Up s3cmd 2.x with DigitalOcean Spaces

  1. Run s3cmd --configure.
  2. Enter your Access and Secret Keys.
  3. Accept the default US region as it doesn't apply with DO Spaces.
  4. S3 Endpoing: nyc3.digitaloceanspaces.com
  5. Template for accessing a bucket: %(bucket)s.nyc3.digitaloceanspaces.com
  6. No need to set an encryption password and accept the default path to GPG (we're not using it in this case).
  7. Yes for "Use HTTPS Protocol" (required by DO Spaces).
  8. Proxy server, leave blank.
set $production cdn.example.com/example-subdirectory;
# Redirect requests to /wp-content/uploads/* to production server
location @prod_uploads {
rewrite "^(.*)/wp-content/uploads/(.*)$" "https://$production/wp-content/uploads/$2" break;
}
# Rule for handling requests to https://example.com/wp-content/uploads/
location ~ "^/wp-content/uploads/(.*)$" {
try_files $uri @prod_uploads;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment