. */ declare(strict_types=1); namespace App\EventSubscriber; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Security\Http\HttpUtils; /** * The purpose of this event listener is (if enabled) to redirect all requests to https. */ final class RedirectToHttpsSubscriber implements EventSubscriberInterface { public function __construct( #[Autowire('env(bool:REDIRECT_TO_HTTPS)')] private readonly bool $enabled, private readonly HttpUtils $httpUtils) { } public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['onKernelRequest', 0], ]; } public function onKernelRequest(RequestEvent $event): void { //If the feature is disabled, or we are not the main request, we do nothing if (!$this->enabled || !$event->isMainRequest()) { return; } $request = $event->getRequest(); //If the request is already https, we do nothing if ($request->isSecure()) { return; } //Change the request to https $new_url = str_replace('http://', 'https://' ,$request->getUri()); $event->setResponse($this->httpUtils->createRedirectResponse($event->getRequest(), $new_url)); } }