PHP how to get the base domain/url?

PHP how to get the base domain/url?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Stripping the Path: How to Extract Just the Base Domain in PHP

When building applications, you often need a canonical URL to redirect users, construct API endpoints, or inject into meta tags. A common starting point is using $_SERVER['HTTP_HOST']. In many scenarios, this variable returns exactly what you expect. However, as soon as your application logic moves beyond the root directory—say, you are rendering a view from /sub/dashboard—the behavior becomes tricky depending on how you interpret the result.

The source code provided in your scenario demonstrates a standard approach to building a full URL:

function url() {
    if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    } else {
        $protocol = 'http';
    }
    return $protocol . "://" . $_SERVER['HTTP_HOST'];
}

This function correctly identifies the protocol and the host. The problem arises because $_SERVER['HTTP_HOST'] contains the hostname only, but if you are trying to reconstruct a full URL including the script path using something like $_SERVER['SCRIPT_NAME'], you end up concatenating the subdirectory into your base link. If your goal is strictly example.com regardless of whether you are accessing /sub/page.php or /home.php, you need to strip the script name and query string from the full URL generated by $_SERVER['REQUEST_URI'].

The most robust way to handle this without relying on fragile manual string concatenation is to parse the request URI. You can combine the protocol, host, and the path from the server variables, then use a regex or a dedicated parser to isolate the base domain. Here is a more resilient pattern:

function getBaseDomain() {
    $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $uri = parse_url('http://' . $host . $_SERVER['REQUEST_URI'], PHP_URL_PATH);
    
    // Remove leading slash if present
    return $scheme . "://" . $host; 
}

Actually, a cleaner approach that avoids the complexity of parsing REQUEST_URI manually is to simply ensure you never concatenate $_SERVER['SCRIPT_NAME'] into your base URL in the first place. The variable $_SERVER['HTTP_HOST'] is specifically designed to return just the domain name (e.g., example.com or www.example.com). If you are seeing a path appended, it is almost certainly because your code is explicitly joining SCRIPT_NAME or PHP_SELF to this host variable.

To strictly get the base domain without any subdirectory logic, simply return the concatenation of the scheme and HTTP_HOST. Do not append anything else. If you need to canonicalize URLs for SEO purposes (removing www or trailing slashes), that is a separate normalization step, but extracting the raw base URL requires no path manipulation at all.

function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    return rtrim($protocol . '://' . $_SERVER['HTTP_HOST'], '/');
}

The rtrim is essential here because some legacy configurations might add a trailing slash to the host variable, which can break relative asset loading. By stopping your logic at HTTP_HOST, you guarantee that subdirectories like /sub never infiltrate your base URL string. This ensures consistency whether a user hits the root or a deep nested route.

For modern Laravel projects, this manual parsing is often unnecessary. If you are using the framework's built-in helpers, url() provides a cleaner abstraction that respects your configured APP_URL. However, if you are writing legacy PHP or need to support multiple environments with different entry points, understanding these server variables remains critical for maintaining correct redirects and asset paths.

If you find yourself needing to manage complex URL logic across a large codebase, consider how your routing system handles base paths. Ensuring that your application configuration explicitly defines the base path (e.g., in config/app.php or environment files) can prevent these runtime variable discrepancies entirely.

Our network