public function handleCanonicalURLRedirection(SymfonyRequest $r, Site $site)
    {
        $globalConfig = $this['config'];
        $siteConfig = $site->getConfigRepository();

        if ($globalConfig->get('concrete.seo.redirect_to_canonical_url') && $siteConfig->get('seo.canonical_url')) {
            $requestUri = $r->getUri();

            $path = parse_url($requestUri, PHP_URL_PATH);
            $trailingSlash = substr($path, -1) === '/';

            $url = UrlImmutable::createFromUrl($requestUri, $trailingSlash);

            $mainCanonical = null;
            foreach (['seo.canonical_url', 'seo.canonical_url_alternative'] as $key) {
                $canonicalUrlString = $siteConfig->get($key);
                if (!$canonicalUrlString) {
                    continue;
                }
                $canonicalUrl = UrlImmutable::createFromUrl(
                    $canonicalUrlString,
                    (bool) $globalConfig->get('concrete.seo.trailing_slash')
                );
                // Set the parts of the current URL that are specified in the canonical URL, including host,
                // scheme, port. Set scheme first so that our port can use the magic "set if necessary" method.
                $canonical = $url
                    ->setScheme($canonicalUrl->getScheme()->get())
                    ->setHost($canonicalUrl->getHost()->get())
                    ->setPort($canonicalUrl->getPort()->get())
                ;
                // Now we have our current url, swapped out with the important parts of the canonical URL.
                // If it matches, we're good.
                if ($canonical == $url) {
                    return null;
                }
                if ($mainCanonical === null) {
                    $mainCanonical = $canonical;
                }
            }

            $response = new RedirectResponse($mainCanonical, '301');

            return $response;
        }
    }