33

How can I redirect to an external URL within a symfony action?

I tried this options :

1- return $this->redirect("www.example.com");

Error : No route found for "GET /www.example.com"

2- $this->redirect("www.example.com");

Error : The controller must return a response (null given).

3- $response = new Response();
$response->headers->set("Location","www.example.com");
return $response

No Error but blank page !

SirDerpington
  • 11,260
  • 4
  • 49
  • 55
Saman Mohamadi
  • 4,454
  • 4
  • 38
  • 58

2 Answers2

51

Answer to your question is in official Symfony book.

http://symfony.com/doc/current/book/controller.html#redirecting

public function indexAction()
{
    return $this->redirect('http://stackoverflow.com');
    // return $this->redirect('http://stackoverflow.com', 301); - for changing HTTP status code from 302 Found to 301 Moved Permanently
}

What is the "URL"? Do you have really defined route for this pattern? If not, then not found error is absolutelly correct. If you want to redirect to external site, always use absolute URL format.

kba
  • 4,190
  • 2
  • 15
  • 24
  • What you've provided is redirect to existing URL in application. If you look closely at OP's title, you will notice that he is asking about *external* Url. Take a look at my answer. – Artamiel Apr 20 '15 at 14:06
  • You are right. I have badly copy an example from official doc. – kba Apr 20 '15 at 14:12
  • This does NOT answer the question, which is to redirect to an EXTERNAL url – David Soussan Mar 15 '16 at 10:39
  • I'm sorry but I think `http://stackoverflow.com` is an EXTERNAL URL :). Can you explain more deeply why do you think it's bad answer? – kba Mar 15 '16 at 20:02
  • 1
    This answer calls the Symfony2 `Controller::redirect` method, which is the equivalent of calling `new RedirectResponse` when navigating to a symfony route. https://github.com/symfony/framework-bundle/blob/2.8/Controller/Controller.php#L80 Both of which are the same as specifying `header('Location: http://www.example.com');` Effectively the issue was that `http://` was not included in the OP's question, as all `RedirectResponse` does is extend `Response` and calls `$this->headers->set('Location', $url)` and setting the content to include a `meta refresh` as the content body. – Will B. Jul 11 '16 at 15:56
33

You have to use RedirectResponse instead of Response

use Symfony\Component\HttpFoundation\RedirectResponse;

And then:

return new RedirectResponse('http://your.location.com');
Artamiel
  • 3,652
  • 2
  • 19
  • 24