Alter Drupal final HTML output to change all paths from relative to absolute URL

The task is to change all path values in HTML attributes src and href from relative to absolute URL in a Drupal site by altering Drupal final HTML output.

We can just use the following codes to target links:

      
/**
 * Implements hook_url_outbound_alter().
 */
function mycustommodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (isset($_GET['getpagefordomain']) && $_GET['getpagefordomain'] == 1) {
    $options['absolute'] = TRUE;
  }
}
      
    

Note: the getpagefordomain query string parameter is used to easily toggle this feature via URL address. But the codes above is not guaranteed to cover all the path values in HTML attribute href and we need also to cover the path values in src attribute. The sure solution is to change the paths via Drupal final HTML output.

We will use hook_process_html to access the final Drupal final HTML output. The following codes should accomplish the task:

      
/**
 * Implements hook_process_HOOK().
 */
function mycustommodule_process_html(&$variables) {
  if (isset($_GET['getpagefordomain']) && $_GET['getpagefordomain'] == 1) {
    mycustommodule_replace_href_src_absolute($variables['head']);
    mycustommodule_replace_href_src_absolute($variables['styles']);
    mycustommodule_replace_href_src_absolute($variables['scripts']);
    mycustommodule_replace_href_src_absolute($variables['page_top']);
    mycustommodule_replace_href_src_absolute($variables['page']);
    mycustommodule_replace_href_src_absolute($variables['page_bottom']);
  }
}

/**
 * Replace href and src values from relative to absolute URL.
 */
function mycustommodule_replace_href_src_absolute(&$html) {
  global $base_url;
  $baseurl = "$base_url/";
  //$baseurl = url('', array('absolute' => TRUE));
  $html = str_replace('src="//', 'src="@@', $html);
  $html = str_replace("src='//", "src='@@", $html);
  $html = str_replace("src='/", "src='$baseurl", $html);
  $html = str_replace('src="/', "src=\"$baseurl", $html);
  $html = str_replace('href="//', 'href="@@', $html);
  $html = str_replace("href='//", "href='@@", $html);
  $html = str_replace("href='/", "href='$baseurl", $html);
  $html = str_replace('href="/', "href=\"$baseurl", $html);
  $html = str_replace("src='@@", "src='//", $html);
  $html = str_replace('src="@@', 'src="//', $html);
  $html = str_replace("href='@@", "href='//", $html);
  $html = str_replace('href="@@', 'href="//', $html);
}
      
    
Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.