How to use a relative path to your JS and CSS in Drupal 7

By default, Drupal uses an absolute path, and will insert your domain name into the path to your JS and CSS files.

You can override this, in template.php, like so:

function YOURTHEME_process_html(&$vars) {

  //convert absolute URLs (https://www...) into relative (/some/path) for JS and CSS only
  foreach (array('scripts','styles') as $replace) {
      if (!isset($vars[$replace])) {
          continue;
      }

      $vars[$replace] = str_replace("https://stage.example.com", '', $vars[$replace]);
      $vars[$replace] = str_replace("https://www.example.com", '', $vars[$replace]);
  }

}
Published
Categorized as Drupal