Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

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?

Upvotes: 0

Views: 5405

Answers (2)

Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

In my question I didn't specify the url was being generated from a Command, because I didn't think it was relevant.

Based on the answer by @brevis I now know what to search for (router context), which brought me to this page: https://symfony.com/doc/current/console/request_context.html

On that page it says you should should add this:

# config/services.yaml
parameters:
    router.request_context.host: 'example.org'
    router.request_context.scheme: 'https'
    router.request_context.base_url: 'my/path'
    asset.request_context.base_path: '%router.request_context.base_url%'
    asset.request_context.secure: true

Which is the simpler answer for this specific problem.

Upvotes: 1

brevis
brevis

Reputation: 1201

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');
}

Upvotes: 2

Related Questions