public function buildBaseUrl()
    {
        $domain = $this->request->getScheme() . '://' . $this->request->getHttpHost();

        $url = $this->request->getScriptName();

        // We only want to remove the first occurrence of our base path, and only if base path is valid
        if ($this->getBasePath()) {
            $basePathPos = strpos($url, $this->getBasePath());
            if ($basePathPos !== false) {
                $url = substr_replace($url, '', $basePathPos, strlen($this->getBasePath()));
            }
        }

        // And we want to remove the script name separately, since it's possible base path is empty
        $url = str_replace($this->getScriptName(), '', $url);

        $this->baseUrl = $domain . '/' . ltrim($url, '/');

        return $this;
    }