Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony redirect to external URL

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 !

like image 650
Saman Mohamadi Avatar asked Aug 31 '25 22:08

Saman Mohamadi


2 Answers

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.

like image 166
kba Avatar answered Sep 03 '25 20:09

kba


You have to use RedirectResponse instead of Response

use Symfony\Component\HttpFoundation\RedirectResponse;

And then:

return new RedirectResponse('http://your.location.com');
like image 26
Artamiel Avatar answered Sep 03 '25 20:09

Artamiel