Drupal 8 /9 : convert link media file to absolute url

Profile picture for user a.berramou
Azz-eddine BERRAMOU 24 March, 2022

Drupal by default set the path for all files to relative path something like /sites/default/files/2022-03/dummy.pdf so if you use your Drupal site as an API (Rest or graphQl) and sent the wysiwyg text (Body for instance) contain files then your front site (https://www.front-site.com) will redirect you to the wrong path because your front server will look at https://www.front-site.com/sites/default/files/2022-03/dummy.pdf  which it doesn't exits on your front server.

So how to convert all files path to absolute path?

To change path of files we need to preprocess file_link hook and make the url absolute, to do so we will use hook_preprocess_HOOK like the following:

<?php

use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK().
 */
function [MODULE_NAME]_preprocess_file_link(&$variables) {
  if (isset($variables['link']['#url']) && $variables['link']['#url'] instanceof Url) {
    // Set url absolute to true.
    $variables['link']['#url']->setAbsolute(TRUE);
  }
}

Now you will have 

file url after hook
File url after hook implementation

Instead of

file url before hook
File url before hook implementation

I hope you find this article helpful.