Symfony 重定向到外部 URL

Symfony redirect to external URL

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

我尝试了这个选项:

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

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

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

错误:控制器必须 return 响应(给定为空)。

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

没有错误,但页面为空白!

您必须使用 RedirectResponse 而不是 Response

use Symfony\Component\HttpFoundation\RedirectResponse;

然后:

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

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

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

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

什么是"URL"?你真的为这个模式定义了路线吗?如果不是,则未发现错误是绝对正确的。 如果您想重定向到外部站点,请始终使用绝对 URL 格式。