Symfony重定向到外部URL

33

我该如何在Symfony动作中重定向到外部URL?

我尝试了以下选项:

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

错误:未找到“GET /www.example.com”的路由

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

错误: 控制器必须返回一个响应(null given)。

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

没有错误,但页面是空白的!


第一个应该能够工作,你能指定你使用的版本吗? - M Khalid Junaid
symfony/symfony v2.6.6 - Saman Mohamadi
2个回答

52

您的问题的答案在官方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"是什么?你真的定义了这个模式的路由吗?如果没有,那么“未找到错误”是绝对正确的。如果您想要重定向到外部网站,请始终使用绝对URL格式。


你提供的是应用程序中重定向到现有URL。如果你仔细看看OP的标题,你会注意到他在问外部Url。请看我的答案。 - Artamiel
你说得对。我从官方文档中糟糕地复制了一个例子。 - kba
这并没有回答问题,问题是要重定向到外部URL。 - David Soussan
很抱歉,但我认为http://stackoverflow.com是一个外部链接 :). 你能更深入地解释一下为什么你认为这是一个不好的答案吗? - kba
1
这个答案调用了Symfony2的Controller::redirect方法,相当于在导航到Symfony路由时调用new RedirectResponse。 https://github.com/symfony/framework-bundle/blob/2.8/Controller/Controller.php#L80 这两者与指定header('Location: http://www.example.com');是一样的。实际上问题在于OP的问题中没有包含http://,因为所有的RedirectResponse所做的就是扩展Response并调用$this->headers->set('Location', $url),并将内容设置为包括一个meta refresh作为内容主体。 - Will B.
显示剩余3条评论

33

你需要使用 RedirectResponse 替代 Response

use Symfony\Component\HttpFoundation\RedirectResponse;

然后:

return new RedirectResponse('http://your.location.com');

这是我能找到的唯一方法,可以使Symfony以这种方式重定向,从而改变浏览器URL(用于内部重定向)。 - beterthanlife
@beterthanlife 我很高兴它对你有帮助。 - Artamiel
1
@Artamiel 谢谢你。这个方法对于外部链接有效。选定的答案出了些问题,无法使用。 - Jamshad Ahmad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接