diff --git a/core/lib/Drupal/Core/Routing/UrlGenerator.php b/core/lib/Drupal/Core/Routing/UrlGenerator.php
index 5e21568be5..df3cf14e15 100644
--- a/core/lib/Drupal/Core/Routing/UrlGenerator.php
+++ b/core/lib/Drupal/Core/Routing/UrlGenerator.php
@@ -323,8 +323,8 @@ public function generateFromRoute($name, $parameters = [], $options = [], $colle
     }
 
     if (!empty($options['prefix'])) {
-      $path = ltrim($path, '/');
-      $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
+      $path = $path === '/' ? $path : ltrim($path, '/');
+      $prefix = empty($path) || $path === '/' ? rtrim($options['prefix'], '/') : $options['prefix'];
       $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
     }
 
