2 * Implements hook_file_url_alter().
4 function {{ machine_name }}_file_url_alter(&$uri) {
5 $user = \Drupal::currentUser();
7 // User 1 will always see the local file in this example.
8 if ($user->id() == 1) {
12 $cdn1 = 'http://cdn1.example.com';
13 $cdn2 = 'http://cdn2.example.com';
14 $cdn_extensions = ['css', 'js', 'gif', 'jpg', 'jpeg', 'png'];
16 // Most CDNs don't support private file transfers without a lot of hassle,
17 // so don't support this in the common case.
18 $schemes = ['public'];
20 $scheme = file_uri_scheme($uri);
22 // Only serve shipped files and public created files from the CDN.
23 if (!$scheme || in_array($scheme, $schemes)) {
28 // Public created files.
30 $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
31 $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
34 // Clean up Windows paths.
35 $path = str_replace('\\', '/', $path);
37 // Serve files with one of the CDN extensions from CDN 1, all others from
39 $pathinfo = pathinfo($path);
40 if (isset($pathinfo['extension']) && in_array($pathinfo['extension'], $cdn_extensions)) {
41 $uri = $cdn1 . '/' . $path;
44 $uri = $cdn2 . '/' . $path;