Make Wordpress upload directory outside wordpress root with custom url

I want to change the upload directory for Wordpress from project.dev/wp-content/uploads to cdn.project.dev

Where subdomain cdn has DocumentRoot: HostPath/project.dev/cdn while Wordpress is located at HostPath/project.dev/public_html

Any help is much appreciated.

Topic wp-config uploads php Wordpress

Category Web


You can create a very simple plug-in to meet your needs. Here is one based on the now-defunct directory-control plugin, previously available at https://github.com/johnbillion/directory-control.

  1. In your plugins directory, create a directory called custom_upload_dir
  2. In that directory, create the following file called custom_upload_dir.php

    <?php
    /*
    Plugin Name:  Custom Upload Directory
    Author URI:   https://wordpress.stackexchange.com/a/253797/111682
    */
    function custom_upload_dir_impl( $uploads ) {
        if ( defined( 'WP_UPLOAD_DIR' ) ) {
            $uploads['path'] = str_replace( WP_CONTENT_DIR . '/uploads', WP_UPLOAD_DIR, $uploads['path'] );
            $uploads['basedir'] = str_replace( WP_CONTENT_DIR . '/uploads', WP_UPLOAD_DIR, $uploads['basedir'] );
        }
        return $uploads;
    }
    add_filter( 'upload_dir',     'custom_upload_dir_impl', 1 );
  1. In your wp-config.php file define the WP_UPLOAD_DIR constant used by the plugin.
  2. In Wordpress Admin, enable the plug-in

If all you want to do is to have a "cdn" type url, the easiest solution that do not require any programing is to make HostPath/project.dev/cdn a symlink to project.dev/wp-content/uploads. This way for theOS both paths are essentially the same. This should be easy to do if you are in full control of the server and/or have SSH access, or might require help from your hosting if you do not have this kind on access.

Another option if you have control on the web server configuration is to map the "document root" of the cdn.project.dev to the dev/wp-content/uploads directory.

Putting the uploaded files outside of the wordpress directory tree,as the question literally asks, is not a great idea as it is likely to break all kinds of external tools like backup utilities.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.