# Serve Media and Static Files From a CDN Domain

> Rewrites the URLs of your uploads, theme and plugin files to a CDN or pull-zone domain you set, so images, CSS and JavaScript are delivered from the CDN while pages are still served by your site.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: cdn, images, static-files
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-serve-uploads-from-cdn/

## Code

```php
// Your CDN address, without a trailing slash.
$wpide_cdn_url = 'https://cdn.example.com';
// Folders whose files are served from the CDN.
$wpide_cdn_dirs = array( 'wp-content/uploads', 'wp-content/themes', 'wp-content/plugins', 'wp-includes' );

if ( 'https://cdn.example.com' !== $wpide_cdn_url ) {
    $wpide_cdn_rewrite = function ( $url ) use ( $wpide_cdn_url, $wpide_cdn_dirs ) {
        if ( ! is_string( $url ) || is_admin() || is_preview() || is_customize_preview() ) {
            return $url;
        }

        $site = untrailingslashit( set_url_scheme( site_url(), 'https' ) );

        foreach ( $wpide_cdn_dirs as $dir ) {
            foreach ( array( $site, set_url_scheme( $site, 'http' ) ) as $origin ) {
                if ( 0 === strpos( $url, $origin . '/' . $dir . '/' ) ) {
                    return untrailingslashit( $wpide_cdn_url ) . substr( $url, strlen( $origin ) );
                }
            }
        }

        return $url;
    };

    add_filter( 'wp_get_attachment_url', $wpide_cdn_rewrite, 99 );
    add_filter( 'script_loader_src', $wpide_cdn_rewrite, 99 );
    add_filter( 'style_loader_src', $wpide_cdn_rewrite, 99 );
    add_filter( 'wp_calculate_image_srcset', function ( $sources ) use ( $wpide_cdn_rewrite ) {
        foreach ( (array) $sources as $width => $source ) {
            $sources[ $width ]['url'] = $wpide_cdn_rewrite( $source['url'] );
        }
        return $sources;
    }, 99 );
    add_filter( 'the_content', function ( $content ) use ( $wpide_cdn_url ) {
        $uploads = wp_get_upload_dir();
        $from    = set_url_scheme( $uploads['baseurl'], 'https' );
        $to      = untrailingslashit( $wpide_cdn_url ) . wp_make_link_relative( $from );

        return str_replace( array( $from, set_url_scheme( $from, 'http' ) ), $to, $content );
    }, 99 );
}
```

## Notes

Create a pull zone that points to your site first and set $wpide_cdn_url to its address; admin pages and the block editor keep using your own domain.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Serve Media and Static Files From a CDN Domain" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
