symfony 从一个域重定向到另一个域

symfony redirect from one domain to another

我有一个 Symfony 4.2 站点,它在两个子域上提供内容:

a.example.com

b.example.com

如何将 a 上对 /resetting/reset/ 的请求重定向到 b,同时保留查询字符串?

我尝试了下面的方法,但它没有做任何事情 - 即当我点击 a.example.com/resetting/reset 它只是停留在那里。没有错误。

resetting:
    host: ^%a_domain%$
    path: ^/resetting/reset/
    controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
    defaults:
        path: '%b_domain%/resetting/reset/'
        permanent: true
        keepQueryParams: true

如有任何想法,我们将不胜感激!

我无法使用 yaml 方法,所以我用自定义重定向操作覆盖了路由,如下所示:

/**
 * @Route("/resetting/reset/{token}",
 *     name="fos_user_resetting_reset_override",
 *     host="{domain}",
 *     defaults={"domain"="%a_domain%"},
 *     requirements={"domain"="(%a_domain%)"},
 * )
 */
public function redirectResettingRouteToBDomain(string $token): RedirectResponse
{
    // generate the current url with an absolute path
    $path = $this->generateUrl(
        'fos_user_resetting_reset',
        ['token' => $token],
        UrlGeneratorInterface::ABSOLUTE_PATH
    );

    // replace A_DOMAIN with B_DOMAIN in the path
    $domain = preg_replace(
        '/' . preg_quote(getenv('A_DOMAIN'), '/') . '/',
        getenv('B_DOMAIN'),
        $this->getRequest()->server->get('HTTP_HOST')
    );

    // ensure the redirect works on http and https
    $url = '//' . $domain . $path;

    return $this->redirect($url);
}

请注意,我为 A_DOMAINB_DOMAIN 设置了环境变量,然后将它们作为 a_domainb_domain 参数提供。

本质上,上面的控制器操作仅在 A_DOMAIN 上触发,覆盖 B_DOMAIN 的默认 fos_user_resetting_reset 路由,然后重定向请求。

使用路由器更改主机如下class:

$this->router->getContext()->setHost($host);
//$url = $this->router->generate('routeName');
//return $event->setResponse(new RedirectResponse($url));
return $this->redirectToRoute('routeName');