<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class LowercaseRedirectSubscriber implements EventSubscriberInterface
{
private const BLACKLIST_REGEX = [
'/^\/wp-/', // Wordpress naked URLs
'/^\/edition\//', // WPSY-wrapped Wordpress URLs
'/^\/_wdt/', // Symfony web toolbar
'/^\/_profiler/', // Symfony profiler
];
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$path = $request->getPathInfo();
// Check for blacklisted URLs. If matches, return.
foreach (self::BLACKLIST_REGEX as $regex) {
if (preg_match($regex, $path)) {
return;
}
}
// Check for uppercase characters in path. Otherwise, return.
if (!preg_match('/[A-Z]/', $path)) {
return;
}
// Redirect to lowercase version
$url = $request->getSchemeAndHttpHost().$request->getBaseUrl().mb_strtolower($request->getPathInfo());
if (null !== $qs = $request->getQueryString()) {
$url .= '?'.$qs;
}
$event->setResponse(
new RedirectResponse(
$url,
Response::HTTP_MOVED_PERMANENTLY
)
);
}
public static function getSubscribedEvents(): array
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}