How SunSitemap Auto-Detects the Base URL in PHP

SunSitemap automatically determines the base URL by inspecting $_SERVER['HTTPS'] and $_SERVER['HTTP_HOST'] in its constructor when no URL is explicitly provided.

The msbatal/php-sitemap-generator repository provides a lightweight PHP class for generating XML sitemaps. Understanding how SunSitemap handles base URL detection is essential for deploying the library correctly across different environments, from traditional web servers to command-line interfaces. This article examines the automatic detection mechanism implemented in the core class and explains how developers can override it when necessary.

The Auto-Detection Logic in SunSitemap.php

SunSitemap determines the site’s base URL during object instantiation. Inside the __construct method of SunSitemap.php (lines 111–120), the class checks whether a $baseUrl argument was supplied. When the parameter is omitted or null, the constructor builds the URL dynamically from the current request’s server environment variables.

The implementation follows this logic:

if (!empty($baseUrl)) {
    $this->baseUrl = $baseUrl . '/';
} else {
    // Auto-detect base URL
    $this->baseUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') .
                     '://' . $_SERVER['HTTP_HOST'] . '/';
}

This conditional block ensures that a trailing slash is always appended to maintain consistent URL concatenation throughout the sitemap generation process. The detection relies entirely on standard PHP superglobal data available during web requests.

Server Variables Used for Detection

SunSitemap parses two specific $_SERVER indices to construct a fully qualified URL. This approach requires no configuration files or hardcoded domains when running within a web context.

HTTPS Scheme Detection

The class checks for the presence of $_SERVER['HTTPS'] to determine the protocol. If the key exists, the constructor appends the letter s to create https://. When absent, the scheme defaults to http://. This mirrors standard Apache and Nginx configurations where SSL termination sets this server variable.

HTTP_HOST Resolution

The domain component originates from $_SERVER['HTTP_HOST'], which typically contains the hostname and optional non-standard port (e.g., example.com or localhost:8080). SunSitemap concatenates this value directly after the scheme, then appends a trailing slash to form the complete base URL.

Explicit vs. Automatic Base URL Configuration

While SunSitemap auto-detects the base URL by default, developers can supply a custom string to bypass server variable inspection. This is critical for CLI scripts, cron jobs, or containerized environments where $_SERVER may be unavailable or populated with incorrect values.

Automatic Detection (Web Context)

For standard web applications, instantiate the class without arguments to leverage automatic discovery:

<?php
require 'SunSitemap.php';

// Auto-detect from current request
$sitemap = new SunSitemap();
$sitemap->addUrl('products/item-1.html')
        ->addUrl('blog/post-title', '2024-01-15', 'weekly', '0.6')
        ->createSitemap()
        ->updateRobots();

echo "Detected base URL: {$sitemap->baseUrl}\n";

Manual Override (CLI or Custom Context)

When running outside a web server or when generating sitemaps for a different domain, pass the base URL explicitly:

<?php
require 'SunSitemap.php';

// Force specific base URL
$customBase = 'https://cdn.example.com';
$sitemap = new SunSitemap($customBase);
$sitemap->addUrl('static/page.html')
        ->createSitemap();

echo "Forced base URL: {$sitemap->baseUrl}\n";

Supplying a string to the constructor skips the $_SERVER inspection entirely, using the provided value plus a trailing slash as the foundation for all subsequent URL additions.

Summary

  • SunSitemap automatically constructs the base URL in SunSitemap.php (lines 111–120) when the constructor receives no $baseUrl argument.
  • The detection mechanism concatenates http or https (based on $_SERVER['HTTPS']), the :// delimiter, and $_SERVER['HTTP_HOST'].
  • A trailing slash is automatically appended to ensure proper URL joining during sitemap generation.
  • Developers can override auto-detection by passing a fully qualified URL string to the constructor, which is required for CLI execution environments.
  • The logic depends on standard PHP server variables, making it compatible with Apache, Nginx, and most PHP-FPM configurations without additional configuration files.

Frequently Asked Questions

What happens if $_SERVER['HTTP_HOST'] is not set?

If $_SERVER['HTTP_HOST'] is undefined—common in CLI scripts or improperly configured servers—the constructor will generate a malformed URL starting with http:// or https:// followed immediately by a slash. You should always provide an explicit $baseUrl when executing SunSitemap outside a web server context to avoid empty host values in your generated sitemap.

Can I use SunSitemap with a custom port in the base URL?

Yes. Because $_SERVER['HTTP_HOST'] includes non-standard ports (e.g., localhost:8080), SunSitemap automatically incorporates them during auto-detection. If you are manually specifying the base URL, simply include the port in your string: new SunSitemap('http://localhost:8080').

Does SunSitemap support detecting HTTPS behind a reverse proxy?

The default auto-detection checks $_SERVER['HTTPS'], which may be unset behind load balancers or reverse proxies that handle SSL termination. In such configurations, the class will incorrectly default to http:// unless you explicitly provide the https:// base URL to the constructor or configure your web server to set HTTPS appropriately for downstream PHP processes.

Is the trailing slash always added to the base URL?

Yes. Both the auto-detection branch and the explicit $baseUrl branch append a trailing slash in the constructor. This ensures consistent behavior when the addUrl() method concatenates relative paths, preventing double slashes or missing path separators in the final XML output.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →