Symfony重定向到外部URL

时间:2015-04-20 12:10:45

标签: symfony redirect header response

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

我尝试了这个选项:

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

错误:未找到" GET /www.example.com"

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

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

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

没有错误但是空白页面!

2 个答案:

答案 0 :(得分:30)

您的问题的答案在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
}

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

答案 1 :(得分:21)

您必须使用 RedirectResponse 而不是响应

use Symfony\Component\HttpFoundation\RedirectResponse;

然后:

return new RedirectResponse('http://your.location.com');
相关问题