Skip to content

Commit

Permalink
refactor: Ensure that URLs that are a site index URL and have a path …
Browse files Browse the repository at this point in the history
…prefix strip trailing slashes as appropriate ([#717](#717)) ([#5675](craftcms/cms#5675))
  • Loading branch information
khalwat committed Dec 28, 2024
1 parent c206b27 commit b57acfe
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/helpers/UrlHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public static function absoluteUrlWithProtocol($url): string
if ($generalConfig->addTrailingSlashesToUrls && !preg_match('/(.+\?.*)|(\.[^\/]+$)/', $url)) {
$url = rtrim($url, '/') . '/';
}
if (!$generalConfig->addTrailingSlashesToUrls && !$preserveTrailingSlash) {
if (!$generalConfig->addTrailingSlashesToUrls && (!$preserveTrailingSlash || self::urlIsSiteIndex($url))) {
$url = rtrim($url, '/');
}

Expand Down Expand Up @@ -219,6 +219,34 @@ public static function urlHasSubDir(string $url): bool
return !empty(parse_url(trim($url, '/'), PHP_URL_PATH));
}

/**
* See if the url is a site index, and if so, strip the trailing slash
* ref: https://github.com/craftcms/cms/issues/5675
*
* @param string $url
* @return bool
*/
public static function urlIsSiteIndex(string $url): bool
{
$sites = Craft::$app->getSites()->getAllSites();
$result = false;
foreach ($sites as $site) {
$sitePath = parse_url(self::siteUrl('/', null, null, $site->id), PHP_URL_PATH);
if (!empty($sitePath)) {
// Normalizes a URI path by trimming leading/ trailing slashes and removing double slashes
$sitePath = '/' . preg_replace('/\/\/+/', '/', trim($sitePath, '/'));
}
// Normalizes a URI path by trimming leading/ trailing slashes and removing double slashes
$url = '/' . preg_replace('/\/\/+/', '/', trim($url, '/'));
// See if this url ends with a site prefix, and thus is a site index
if (str_ends_with($url, $sitePath)) {
$result = true;
}
}

return $result;
}

/**
* Return the siteUrlOverride setting, which can be a string or an array of site URLs
* indexed by the site handle
Expand Down

0 comments on commit b57acfe

Please sign in to comment.