根据内核请求重定向

mAt*_*AtZ 3 php symfony

我的项目的网站可以通过子域访问,例如https://1234.example.com子域由四个数值组成,代表特殊用户实体的 id。因此,当发出请求时,我必须检查该 id 是否真的存在,如果不存在,我想重定向到根 url https://www.example.com。如果用户使用了正确的 id,则无需执行任何操作。我做了一个事件监听器并检查了 id 的存在。这像预期的那样工作。但是重定向到根 url 将不起作用:

public function onKernelRequest(GetResponseEvent $event)
{
    if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
        return;
    }

    $request = $event->getRequest();

    $hostArray = explode('.', $request->getHost());
    $subdomain = $hostArray[0];

    array_shift($hostArray);
    $host = implode('.', $hostArray);

    if (!is_numeric($hostArray[0])) {
        return new RedirectResponse($host);
    }

    $user = $this->userManager->findUserBy(['id' => $subdomain]);
    if (null === $user) {
        return new RedirectResponse($host);
    }
}
Run Code Online (Sandbox Code Playgroud)

即使 id 不存在,url 也不会改变。当我逐步调试代码时,我可以看到他到达了 RedirectResponse。但什么也没有发生。

有任何想法吗?

Jak*_*las 5

监听器不应该返回任何东西。如果要触发重定向,请对事件设置响应:

public function onKernelRequest(GetResponseEvent $event)
{
    if (!$event->isMasterRequest()) {
        return;
    }

    $hostArray = explode('.', $event->getRequest()->getHost());
    $subdomain = $hostArray[0];

    array_shift($hostArray);
    $host = implode('.', $hostArray);

    if (is_numeric($subdomain) && $user = $this->userManager->findUserBy(['id' => $subdomain])) {
        // you can pass the user as an attribute if you need him later
        $event->getRequest()->attributes->set('user', $user);

        return;
    }

    $event->setResponse(new RedirectResponse($host));
}
Run Code Online (Sandbox Code Playgroud)