Symfony重定向到外部URL

Sam*_*adi 19 redirect header response symfony

如何在symfony操作中重定向到外部URL?

我试过这个选项:

1- return $this->redirect("www.example.com");
Run Code Online (Sandbox Code Playgroud)

错误:找不到"GET /www.example.com"的路由

2- $this->redirect("www.example.com");
Run Code Online (Sandbox Code Playgroud)

错误:控制器必须返回响应(给定null).

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

没有错误但空白页面!

kba*_*kba 32

您的问题的答案在Symfony官方书中.

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
}
Run Code Online (Sandbox Code Playgroud)

什么是"URL"?你有这个模式真正定义的路线吗?如果没有,那么找不到错误是绝对正确的.如果要重定向到外部站点,请始终使用绝对URL格式.


Art*_*iel 25

您必须使用RedirectResponse而不是Response

use Symfony\Component\HttpFoundation\RedirectResponse;
Run Code Online (Sandbox Code Playgroud)

然后:

return new RedirectResponse('http://your.location.com');
Run Code Online (Sandbox Code Playgroud)