How to force image URLs as HTTPS? There are a few places where I am calling ImageStyle::load('style')-&gt;buildUrl($uri) to get a physical file path of an image.

After enabling HTTPS and forcing all traffic to use HTTPS, I noticed that this will only return http:// at the start of the url, and not https:// causing mixed mode flag in the browser.

Is there a way to do this and get the correct protocol? Can I not just obtain the relative path to the file instead? I notice that this method has hardcoded 'absolute' =&gt; TRUE when building the url to return.

Edit: fields using the normal rendering method i.e. {{ content.field_image }} have the correct protocol and do not cause an issue.

Here is the code I am using to generate the variable:

/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&amp;$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node-&gt;bundle();

  if ($bundle =='homepage' &amp;&amp; $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node-&gt;get('field_hero_image')-&gt;getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('homepage_hero')-&gt;buildUrl($entity-&gt;field_image-&gt;entity-&gt;getFileUri());
    }
  }
}


In the node view mode twig template:

  {% if node.field_hero_image is not empty %}
    &lt;div class="hero__graphic" style="background-image: url({{ hero_image }});"&gt;&lt;/div&gt;
  {% endif %}
You can use file_url_transform_relative():

/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by file_create_url().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @see file_create_url()
 */
function file_url_transform_relative($file_url) {