I implemented a controller class in Drupal 8, which redirects to an external site. If I use \Symfony\Component\HttpFoundation\RedirectResponse, I get this error.

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

Using \Drupal\Core\Routing\TrustedRedirectResponse, I get this error.

The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
Returned object class: \Drupal\Core\Routing\TrustedRedirectResponse

What should I do?

  • 2
    See drupal.org/node/2638686 and the related issues, you need to properly deal with cacheablity metadata, we can't help without seeing your specific code
    – Berdir
    Apr 13, 2017 at 21:07

3 Answers 3


Define a controller and redirect to external URL.

Use TrustedRedirectResponse class in case you know that you want to redirect to an external URL. Example below:

use Drupal\Core\Controller\ControllerBase; 
use Drupal\Core\Routing\TrustedRedirectResponse; 
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');  
  • The OP stated there was an error when using TrustedRedirectResponse, which was exactly what happened to me. Their solution below of using SecuredRedirectResponse worked for me Jun 13, 2023 at 14:07

With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class MyControllerClass extends ControllerBase {

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

With a absolute url:

return new RedirectResponse('https://google.com');
  • 1
    It did not help for me. At last, I created a class which extends \Drupal\Component\HttpFoundation\SecuredRedirectResponse. It is required to implement isSafe($url) method to do so. In my case, this is sufficient. Thank you for your answer.
    – MH35
    Apr 13, 2017 at 6:26
  • Extended SecuredRedirectResponse did it for me, thank you! Jun 13, 2023 at 14:06

Alternatively implement hook_redirect_response_alter() (as per #2909182 patch).

Here is the example from redirect_test.module:

use Drupal\redirect\Entity\Redirect;
use Symfony\Component\HttpFoundation\RedirectResponse;

 * Implements hook_redirect_response_alter().
function redirect_test_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $path = 'test/redirect/2/successful';
  $replace = 'test/redirect/other';
  if ($redirect->getRedirect()['uri'] == "internal:/" . $path) {
    $response->setTargetUrl(str_replace($path, $replace, $redirect->getRedirectUrl()->setAbsolute()->toString()));

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.