public function initializeRequest(Application $app, Request $request = null)
    {
        if ($request === null) {
            $request = $app['request_stack']->getCurrentRequest() ?: Request::createFromGlobals();
        }

        // This is where we set the canonical. Note: The protocol (scheme) defaults to 'http',
        // and the path is discarded, as it makes no sense in this context: Bolt always
        // determines the path for a page / record. This is not the canonical's job.
        $canonical = $app['config']->get('general/canonical', $request->server->get('HTTP_HOST'));
        if (strpos($canonical, 'http') !== 0) {
            $canonical = 'http://' . $canonical;
        }

        $canonical = parse_url($canonical);

        if (empty($canonical['host'])) {
            $canonical['host'] = $request->server->get('HTTP_HOST');
        }

        if (empty($canonical['scheme'])) {
            $canonical['scheme'] = 'http';
        }

        if (($request->server->get('HTTPS') == 'on') ||
            ($request->server->get('SERVER_PROTOCOL') == 'https') ||
            ($request->server->get('HTTP_X_FORWARDED_PROTO') == 'https') ||
            ($request->server->get('HTTP_X_FORWARDED_SSL') == 'on')) {
            $canonical['scheme'] = 'https';
        }

        $this->request['canonical'] = sprintf('%s://%s', $canonical['scheme'], $canonical['host']);

        $rootUrl = rtrim($this->urls['root'], '/');
        if ($rootUrl !== $request->getBasePath()) {
            $this->urlPrefix = $request->getBasePath();
        }

        $this->request['protocol'] = $canonical['scheme'];
        $hostname = $request->server->get('HTTP_HOST', 'localhost');
        $this->request['hostname'] = $hostname;
        $current = $request->getBasePath() . $request->getPathInfo();
        $this->setUrl('current', $current);
        $this->setUrl('currenturl', sprintf('%s://%s%s', $canonical['scheme'], $hostname, $current));
        $this->setUrl('hosturl', sprintf('%s://%s', $canonical['scheme'], $hostname));
        $this->setUrl('rooturl', sprintf('%s%s/', $this->request['canonical'], $rootUrl));

        $url = sprintf('%s%s', $this->request['canonical'], $current);
        if (PagerManager::isPagingRequest($request)) {
            $url .= '?' . http_build_query($request->query->all());
        }
        $this->setUrl('canonicalurl', $url);

        $this->requestInitialized = true;
    }