Since version 4.1, Symfony now handles multilingual routing without the need of an external plugin ( https://symfony.com/blog/new-in-symfony-4-1-internationalized-routing ). I've translated my routes with success and all works fine except that when accessing the root url ("/"), Symfony renders a 404 error instead of redirecting to a language folder such as "/en/".
I've done some research but most of what i've found is very outdated (mostly Symfony 2). Also ran into this Symfony 3 Redirect All Routes To Current Locale Version but it seems like an incredibly tedious solution to such a simple problem.
Ideally, i'd also like to redirect the url "/admin" to "/en/admin", but if i can't achieve it i can live with that.
Here's my routes/annotations.yaml file:
controllers:
resource: ../../src/Controller/
type: annotation
prefix:
fr: '/fr'
en: '/en'
de: '/de'
My translations .yaml file:
framework:
#default_locale: '%locale%'
default_locale: 'en'
translator:
paths:
- '%kernel.project_dir%/translations'
fallbacks:
- 'en'
Home route configuration:
@Route("/", name="home")
It looks like you don't have a route matching /
, probably because all your routes are prefixed with a language code.
You can debug this using the command line tool:
php bin/console router:match "/"
If it's successful it should return something like this:
[OK] Route "homepage" matches
+--------------+-------------------------------------------------------------------------------------------+
| Property | Value |
+--------------+-------------------------------------------------------------------------------------------+
| Route Name | homepage |
| Path | / |
| Path Regex | #^/$#sD |
| Host | ANY |
| Host Regex | |
| Scheme | ANY |
| Method | GET |
| Requirements | NO CUSTOM |
| Class | Symfony\Component\Routing\Route |
| Defaults | _controller: App\Controller\HomeController::index |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+-------------------------------------------------------------------------------------------+
If it is not successful there are multiple options. You could create a listener for the "/" route that tries to determine the proper locale and then redirects to the correct one or just always redirect to your "primary" language, eg using a route like this:
homepage:
path: /
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
defaults:
path: /en
permanent: true
edit for clarification:
Your routes/annotation.yaml could then look like this:
controllers:
resource: ../../src/Controller/
type: annotation
prefix:
fr: '/fr'
en: '/en'
de: '/de'
home_fallback:
path: /
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
defaults:
path: /en
permanent: true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.