Search code examples
phpurl-routingsymfony4

Change the host (and port) generated by the symfony/twig url helper


My Symfony app runs as a docker service. So internally it listens to localhost:80. But to reach it from the host machine (on osx, so using docker-machine) I reach it via http://192.168.99.100:8080

Whenever I let twig generate a full url ({{ url('register') }} for example), it generates a url with localhost as the host.

How can I change that to the ip:port combo I need?


Solution

  • You can achieve it by override router context params (host, port) in event listener of kernel.request. Check this answer https://stackoverflow.com/a/31859779/1007620

    Your onRequest() method should looks like this:

    public function onRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }
    
        $this->router->getContext()->setHost('192.168.99.100');
        $this->router->getContext()->setHttpPort('8080');
        $this->router->getContext()->setHttpsPort('8080');
    }