Speed Up Files with Cookieless Domain

Rating: 
+1
-455
-1
Clone this Snippet
Sometimes we just want simple cookie free domain for our files, this simple snippet serves all files (css, js, images, etc.) via domain or subdomain which point to the same drupal root. You can add a variable to settings.php: $conf['custom_cdn'] = 'http://cdn.example.com';
/**
* Implements hook_file_url_alter().
*/
function custom_file_url_alter(&$original_uri) {
  $scheme = file_uri_scheme($original_uri);
 
  // If the current URI is an absolute or protocol-relative URI, return
  // immediately.
  if (($scheme && ($scheme == 'http' || $scheme == 'https')) || drupal_substr($original_uri, 0, 2) == '//') {
    return;
  }
  elseif ($scheme) {
    // Only alter URLs for local stream wrappers. If a file is served
    // remotely, it doesn't make sense to serve it from a CDN.
    $local_schemes = array_keys(file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL));
    if (!in_array($scheme, $local_schemes)) {
      return;
    }
 
    // Attempt to get an external URL using the appropriate wrapper.
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($original_uri)) {
      $uri = str_replace($GLOBALS['base_url'] . '/', '', $wrapper->getExternalUrl());
 
      $original_uri = variable_get('custom_cdn', 'http://cdn.example.com') . '/' . $uri;
      return;
    }
    else {
      return;
    }
  }
  else {
    $original_uri = variable_get('custom_cdn', 'http://cdn.example.com') . '/' . $original_uri;
  }
}
Category: 
Drupal
Drupal Version: 
78