How to set default locale in web root route (/)?

870 Views Asked by At

I have a symfony2 web that I am trying to internationalize. I have routes with /en and /es prefix, but I want sf2 to get a default language if there is no language specified in url.

I defined a root route with this parameters:

home:
    [...]
    prefix:   /{_locale}/
    defaults: { _locale: en }
    requirements:
        _locale: en|es

Then, if i go to 'www.web.com/en' or 'www.web.com/es' it redirects correctly, but if I go to 'www.web.com', it doesn't get the default language ('en'). I am getting an error message No route found for "GET /".

Where's the mistake?

Thanks.

2

There are 2 best solutions below

0
On

You can resolve this problem dublicating the route

In your app/config/routing.yml set 2 different route:

  1. One reserved for homepage /, forcing to a specific Controller
  2. One for all other route (in this example defined with annotation) that have the locale prefix

Insert:

app:
    pattern:   /
    defaults: {_controller: AppBundle:Default:index }

app_locale:
    resource: "@AppBundle/Controller/"
    type:     annotation
    prefix:   /{_locale}
    defaults:  { _locale: en }
0
On

It all looks correct apart from your prefix. Take the trailing slash off because otherwise you routing rule is trying to match www.web.com// meaning you don't actually have a route defined for www.web.com.