3

My host has a high speed NGINX cluster.

I'd like to load my CSS, JS and media files from this cluster. I've followed these steps and added the new static domain via my DNS.

The new DNS settings have propagated successfully and I can access my static files like so http://static.example.com/wp-content/themes/mytheme/style.css.

To begin with, I would like to change the media upload URL. I have tried to add the following snippet to wp-config.php before require_once(ABSPATH.’wp-settings.php’);

/** Path to NGINX cluster */
define( 'UPLOADS', ''.'http://static.example.com/wp-content/uploads' );

When saving the above snippet to wp-config.php and refreshing the site, my media files (images) are loading from the following URL:

http://www.example.com/http://static.example.com/wp-content/uploads/2016/11/image-name.jpg

As you can see, the root URL is loading before the static URL. What's the correct way to set the new upload path? Should I also perform a search and replace for the previous uploads?

I also assume that I change my JS and CSS paths in functions.php, like so?:

// Before
wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array(), '20161025', false );

// After
wp_enqueue_script('script', 'http://static.example.com/wp-content/themes/mytheme/js/script.js', array(), '20161025', false );
2
  • 1
    Looks like it assumes uploads is a folder. Maybe you could filter the output somehow to use another URL
    – jgraup
    Nov 7, 2016 at 12:56
  • Thank you @jgraup. Your comment prompted further investigation and I found the below answer :)
    – Sam
    Nov 11, 2016 at 8:55

2 Answers 2

5

This answer has solved the problem.

You need to add this to your functions.php file.

/**
* Custom media upload URL
* @link https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library
*/
add_filter( 'pre_option_upload_url_path', 'upload_url' );

function upload_url() {
    return 'http://static.yourdomain.com/wp-content/uploads';
}

There's no need to add the original snippet to wp-config.php.

2

The easiest way to tell WordPress to use a sub domain (or another domain) by defining a globals variable in your config.php file.

define('WP_CONTENT_URL', 'http://static.yourdomain.com');

Put this at the very beginning of the config file otherwise it may not work. This will update the url of all resource in wp-content directory.

Read more about it on Wordpress Codex

1
  • This may break some plugins (eg. Yoast SEO). If you intend to use it for CDN, it's best to use a cache plugin that allows you to set a CDN url.
    – Max S.
    Oct 17, 2019 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.