我最近注意到 Symfony 为 Password Angel 生成的链接与实际使用的链接之间存在问题。 当 Symfony 构建 URL 时,没有尾部斜杠,即 /terms,但是,由于 Password Angel 作为静态站点托管在 S3 存储桶中,尾部斜杠是实时 URL 的一部分,即 /terms/。 这会导致两个问题:-
- 不必要的重定向 - 页面中的所有链接都将引用不带尾部斜杠的链接版本,然后用户需要重定向到带尾部斜杠的版本。
-
规范 URL 无效 - 由于我使用 Symfony 为每个页面生成规范 URL,因此它生成的链接版本不带尾部斜杠。 这可能会导致 SEO 问题,因为搜索引擎会
- 访问/条款
- 被重定向到/terms/
- 请注意原始页面位于 /terms
- ...转到步骤 1 - 无限循环...
解决方案 - 装饰 Symfony 路由器
为了解决这个问题,我为 Symfony 默认路由器创建了一个装饰器,并重写了生成方法以在 URL 末尾添加斜杠。 它还检查是否存在 ?这表明存在查询字符串参数,在这种情况下,我在 ? 之前插入 / 。正如我们想要的 /terms/?utm_campaign=... 而不是 /terms?utm_campaign=.../.
<?php 声明(strict_types=1);
命名空间AppService;
使用 SymfonyComponentDependencyInjectionAttributeAsDecorator;
使用 SymfonyComponentHttpKernelCacheWarmerWarmableInterface;
使用 SymfonyComponentRoutingRequestContext;
使用 SymfonyComponentRoutingRouteCollection;
使用 SymfonyComponentRoutingRouter;
使用 SymfonyComponentRoutingRouterInterface;
#[AsDecorator('router.default')]
类 TrailingSlashUrlGenerator 实现 RouterInterface、WarmableInterface
{
公共函数 __construct(
私有只读路由器$urlGenerator,
){}
公共函数生成($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string
{
// 原始网址
$url = $this->urlGenerator->generate($name, $parameters, $referenceType);
// 在任何查询字符串参数之前添加斜杠
$pos = strpos($url, '?');
if ($pos !== false) {
$parts = 爆炸('?', $url, 2);
if (str_ends_with($parts[0], '/') === false) {
$parts[0] .= '/';
返回内爆('?', $parts);
}
}
// 在 URL 末尾添加斜杠
if (str_ends_with($url, '/') === false) {
$url .= '/';
}
返回$url;
}
公共函数匹配(字符串$pathinfo):数组
{
返回 $this->urlGenerator->match($pathinfo);
}
公共函数 getRouteCollection(): RouteCollection
{
返回 $this->urlGenerator->getRouteCollection();
}
公共函数 setContext(RequestContext $context): void
{
$this->urlGenerator->setContext($context);
}
公共函数 getContext(): RequestContext
{
返回 $this->urlGenerator->getContext();
}
公共函数warmUp(字符串$cacheDir,?字符串$buildDir = null):数组
{
返回 [];
}
}
注意:为了将Password Angel作为S3上的静态站点托管,我编写了一个Symfony命令来生成所有页面(全部4个)的静态版本,并将这些上传到S3。 如果您感兴趣,请告诉我,我将发布 Symfony 命令的工作原理。
最初发布于 https://chrisshennan.com/blog/decorate-the-symfony-router-to-add-a-trailing-slash-to-all-urls