Symfony 5 i18n后强制重定向导致错误页/开发工具URL异常
业务背景
我有一个使用Symfony 5作为后端运行的网站,此前仅提供英文版本,现在需要为其新增国际化(i18n)能力。考虑到用户可能已经分享了旧版页面的链接,我们需要将旧链接强制重定向到带语言前缀的新URL,例如:
- 旧地址:
/page-url - 新地址:
/en/page-url
现有实现
首页重定向规则
目前为首页配置的重定向规则位于/config/routes/annotations.yaml:
# /config/routes/annotations.yaml home_fallback: path: / controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction defaults: path: '/%default_locale%' permanent: true
其余页面重定向逻辑
其余页面的重定向逻辑通过自定义事件订阅器实现:
<?php namespace App\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpFoundation\RedirectResponse; class LocaleSubscriber implements EventSubscriberInterface { private $defaultLocale; public function __construct($defaultLocale = 'en') { $this->defaultLocale = $defaultLocale; } public function onKernelRequest(RequestEvent $event) { // if (!$event->isMasterRequest()) return; $request = $event->getRequest(); if (!$request->hasPreviousSession()) { return; } // try to see if the locale has been set as a _locale routing parameter if ($locale = $request->attributes->get('_locale')) { $request->getSession()->set('_locale', $locale); } else { // if no explicit locale has been set on this request, use one from the session $locale = $request->getSession()->get('_locale', $this->defaultLocale); $request->setLocale($locale); $event->setResponse(new RedirectResponse('/' . $locale . '/' . ltrim($request->getRequestUri(), '/'))); } } public static function getSubscribedEvents() { return [ // must be registered before (i.e. with a higher priority than) the default Locale listener KernelEvents::REQUEST => [['onKernelRequest', 20]], ]; } }
现存异常
当出现404错误时(例如手动访问不存在的路径/dzqdzqdzq),URL会出现异常堆叠,最终变为类似127.0.0.1:8000/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/en/dzqdzqdzq的形式。
排查思路
我推测出现重定向死循环的原因是,404场景下Request对象中未携带_locale属性,导致重定向逻辑重复触发。我曾考虑过通过统计请求已被重定向的次数作为规避方案,但认为这并非合理的实现方式。
我也曾考虑另一方案:在/config/routes/annotations.yaml中为所有存量旧路由配置兜底重定向规则,但我希望能有更优的实现方式,因为部分路由携带参数,我不清楚如何通过注解实现参数的自动回填。
如果各位有相关疑问或建议,欢迎提出。
解决方案
死循环根因
问题来自两个核心设计缺陷:
- 事件执行顺序不匹配:Symfony 负责路由匹配、给请求绑定
_locale参数的RouterListener优先级为32,高于你当前订阅器的优先级20,因此会先执行路由匹配。如果请求路径不存在(包括已经加了locale前缀的非法路径),路由匹配失败,永远不会给请求设置_locale属性,触发你的订阅器的else分支,无限重定向。 - 缺少合法locale前缀校验:当前逻辑只要没拿到
_locale就拼接前缀,没有判断路径本身是否已经带有合法的locale段,导致重定向后的/en/xxx请求被重复处理。
具体修复步骤
1. 全局配置允许的locale列表
在config/packages/translation.yaml(或任意参数配置文件)中定义全局参数,避免硬编码:
parameters: app_locales: 'en|zh_CN' # 替换为你实际支持的所有语言标识 default_locale: 'en'
2. 重写LocaleSubscriber
替换现有订阅器代码,增加前缀校验逻辑,调整优先级到路由监听器之前执行:
<?php namespace App\EventSubscriber; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpFoundation\RedirectResponse; class LocaleSubscriber implements EventSubscriberInterface { private $defaultLocale; private $allowedLocales; // 自动从容器注入全局参数 public function __construct(string $defaultLocale, string $allowedLocales) { $this->defaultLocale = $defaultLocale; $this->allowedLocales = explode('|', $allowedLocales); } public function onKernelRequest(RequestEvent $event) { // 仅处理主请求,忽略内嵌子请求(比如模板中渲染的控制器) if (!$event->isMainRequest()) { return; } $request = $event->getRequest(); $pathInfo = $request->getPathInfo(); // 提取纯路径,不带域名、查询参数 // 提取路径第一段,判断是否已经是合法locale $pathSegments = explode('/', ltrim($pathInfo, '/')); $firstSegment = $pathSegments[0] ?? ''; // 已经带合法locale前缀,直接放行交给路由匹配 // 哪怕后续路径不存在,路由匹配失败会直接返回404,不会触发重定向 if (in_array($firstSegment, $this->allowedLocales)) { $request->attributes->set('_locale', $firstSegment); // 同步session存储,方便后续逻辑读取 $request->getSession()->set('_locale', $firstSegment); return; } // 无locale前缀的旧请求,拼接头次重定向,保留原查询参数 $queryString = $request->getQueryString(); $redirectUrl = '/' . $this->defaultLocale . $pathInfo . ($queryString ? '?' . $queryString : ''); // 用301永久重定向,符合SEO要求 $event->setResponse(new RedirectResponse($redirectUrl, 301)); } public static function getSubscribedEvents() { // 优先级设为33,比RouterListener的32高,先处理前缀再走路由匹配 return [ KernelEvents::REQUEST => [['onKernelRequest', 33]], ]; } }
3. 统一调整路由配置
在config/routes/annotations.yaml中给所有控制器路由统一加locale前缀,删掉之前单独写的首页重定向规则(新的订阅器会自动处理首页重定向):
controllers: resource: '../src/Controller/' type: annotation prefix: '/{_locale}' requirements: _locale: '%app_locales%' defaults: _locale: '%default_locale%'
方案说明
- 不需要单独配置带参数的旧路由重定向:当前逻辑会把原路径完整拼接到locale前缀后,不管是静态路径还是带参数的动态路径(比如
/product/123)都会自动重定向到对应带locale的地址,参数自动保留,无需手动回填。 - 404场景处理:用户访问非法旧路径时,会先被重定向到带默认locale的同路径地址,后续路由匹配失败直接返回404,不会再重复拼接前缀。
- 不需要额外统计重定向次数:逻辑从根源上避免了重复重定向的可能,不会出现死循环。
内容的提问来源于stack exchange,提问作者Kaharon

