9

Drupal 7 has drupal_goto() that would allow redirecting to an external url.

The change record indicated that ControllerBase::redirect is the method to be called in D8. https://www.drupal.org/node/2023537

This seems to work with internal drupal URLs but throws an error with external http urls -

[12-Nov-2014 21:00:22 Asia/Kolkata] Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "https://www.facebook.com/dialog/oaut....." does not exist." at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Routing/RouteProvider.php line 147

What would be the ideal equivalent of drupal_goto in D8 to redirect to an external URL?

2 Answers 2

26

With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

With an absolute URL:

use Drupal\Core\Routing\TrustedRedirectResponse;

return new TrustedRedirectResponse('https://google.com');

On a form RedirectResponse doesn't work, then:

With a route name:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...
  
  $form_state->setRedirect('user.page');
}

With an absolute URL:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setResponse(new TrustedRedirectResponse('https://google.com', 302));
  // You can change the response code from 302 to whatever you need
}
2
  • 1
    Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.
    – Pupil
    Mar 7, 2019 at 13:10
  • TrustedRedirectResponse doesn't work. results in exception "The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early" Apr 28, 2023 at 17:22
2

return new RedirectResponse($absolute_url); seems to work

1
  • 1
    Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.
    – Pupil
    Mar 7, 2019 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.