diff --git a/src/Symfony/Component/HtmlSanitizer/Tests/TextSanitizer/UrlSanitizerTest.php b/src/Symfony/Component/HtmlSanitizer/Tests/TextSanitizer/UrlSanitizerTest.php
index c00b8f7dfbfe5..0d366b7b9848f 100644
--- a/src/Symfony/Component/HtmlSanitizer/Tests/TextSanitizer/UrlSanitizerTest.php
+++ b/src/Symfony/Component/HtmlSanitizer/Tests/TextSanitizer/UrlSanitizerTest.php
@@ -274,6 +274,15 @@ public static function provideSanitize(): iterable
'expected' => null,
];
+ yield [
+ 'input' => 'https://trusted.com/link.php',
+ 'allowedSchemes' => ['http', 'https'],
+ 'allowedHosts' => ['subdomain.trusted.com', 'trusted.com'],
+ 'forceHttps' => false,
+ 'allowRelative' => false,
+ 'expected' => 'https://trusted.com/link.php',
+ ];
+
// Allow relative
yield [
'input' => '/link.php',
diff --git a/src/Symfony/Component/HtmlSanitizer/TextSanitizer/UrlSanitizer.php b/src/Symfony/Component/HtmlSanitizer/TextSanitizer/UrlSanitizer.php
index 05d86ba15da8e..0a65873d55577 100644
--- a/src/Symfony/Component/HtmlSanitizer/TextSanitizer/UrlSanitizer.php
+++ b/src/Symfony/Component/HtmlSanitizer/TextSanitizer/UrlSanitizer.php
@@ -132,7 +132,7 @@ private static function matchAllowedHostParts(array $uriParts, array $trustedPar
{
// Check each chunk of the domain is valid
foreach ($trustedParts as $key => $trustedPart) {
- if ($uriParts[$key] !== $trustedPart) {
+ if (!array_key_exists($key, $uriParts) || $uriParts[$key] !== $trustedPart) {
return false;
}
}