Symfony2 Locale on subdomains: Not on the url path


I have two urls – for example:

How I can to set term _locale from url address (en, es, or yy)?

The traditional method is to just rely on the path url for the resource, set a prefix and then let the router automatically set the _locale.

Define a {_locale} prefix on all your routes.

    prefix: /{_locale}/somepage

When an url ” /en/somepage ” comes in and matches that route, the _locale “en” is automatically taken from the url, and set.

However with subdomains the challenge is higher. If you want to set the locale from the domain, the solution is to create a listener for the kernel.request event which parses the domain (available using $request->getHost()) to find the locale and then sets the _locale attribute in the request.

This was taken from Stof’s earlier answer to the problem. I am not having time or interest at this time to post the full solution. However I have heard that there is a better way from ornicar as he implemented it on lichess. You should check that out and comment it here. Thanks!

Here is how it is done from here.

// config.yml
       class: Acme\DemoBundle\Listener\SubdomainListener
           - { name: kernel.event_listener, event: kernel.request, method: onDomainParse }
// SubdomainListener.php
namespace Acme\DemoBundle\Listener;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
class SubdomainListener
   public function onDomainParse(Event $event)
       $request = $event->getRequest();
       $session = $request->getSession();
       // todo: parsing subdomain to detect country
       $session->set('subdomain', $request->getHost());

One thought on “Symfony2 Locale on subdomains: Not on the url path

  1. Pingback: Symfony2 Subdomain Routing - Different Bundles • PHP Help Coding Programming

Leave a Reply

Your email address will not be published. Required fields are marked *