Skip to main content

My goal was to get the base URL and compare it with the URL of the link.  Was it an internal or external link?  You can get the hostname, "{your_domain}", directly from the getHost() request:

$host = \Drupal::request()->getHost();

However, if you need the schema as well, such as https://{your_domain}

$host = \Drupal::request()->getSchemeAndHttpHost();

 

In my situation, I needed to redirect the page to an external site and count the page.  So

$cache = \Drupal::cache();
$cache->deleteAll();

$url = $this->helper->getField(
    $this->node, 'field_document_link'
);

$redirect = new TrustedRedirectResponse($url);
return $redirect->send();

 

Finally, the redirect would only kick in if the link was external.  Which I wrote separately.

Related articles