diff --git a/src/Framework/Features/XmlGenerators/SitemapGenerator.php b/src/Framework/Features/XmlGenerators/SitemapGenerator.php index 64b5690c..38e53a3a 100644 --- a/src/Framework/Features/XmlGenerators/SitemapGenerator.php +++ b/src/Framework/Features/XmlGenerators/SitemapGenerator.php @@ -17,10 +17,12 @@ use Hyde\Foundation\Facades\Routes; use Hyde\Framework\Concerns\TracksExecutionTime; +use function blank; use function filemtime; use function in_array; use function date; use function time; +use function str_starts_with; /** * @see https://www.sitemaps.org/protocol.html @@ -57,7 +59,7 @@ protected function addRoute(Route $route): void { $urlItem = $this->xmlElement->addChild('url'); - $this->addChild($urlItem, 'loc', Hyde::url($route->getOutputPath())); + $this->addChild($urlItem, 'loc', $this->resolveRouteLink($route)); $this->addChild($urlItem, 'lastmod', $this->getLastModDate($route->getSourcePath())); $this->addChild($urlItem, 'changefreq', 'daily'); @@ -103,4 +105,18 @@ protected function getFormattedProcessingTime(): string { return (string) $this->getExecutionTimeInMs(); } + + protected function resolveRouteLink(Route $route): string + { + $baseUrl = Config::getNullableString('hyde.url'); + + if (blank($baseUrl) || str_starts_with($baseUrl, 'http://localhost')) { + // While the sitemap spec requires a full URL, we rather fall back + // to using relative links instead of using localhost links. + + return $route->getLink(); + } else { + return Hyde::url($route->getOutputPath()); + } + } } diff --git a/tests/Feature/Services/SitemapServiceTest.php b/tests/Feature/Services/SitemapServiceTest.php index dddc5e42..e82342eb 100644 --- a/tests/Feature/Services/SitemapServiceTest.php +++ b/tests/Feature/Services/SitemapServiceTest.php @@ -158,4 +158,26 @@ public function test_all_route_types_are_discovered() copy(Hyde::vendorPath('resources/views/homepages/welcome.blade.php'), Hyde::path('_pages/index.blade.php')); copy(Hyde::vendorPath('resources/views/pages/404.blade.php'), Hyde::path('_pages/404.blade.php')); } + + public function testLinksFallbackToRelativeLinksWhenASiteUrlIsNotSet() + { + config(['hyde.url' => null]); + + $service = new SitemapGenerator(); + $service->generate(); + + $this->assertEquals('404.html', $service->getXmlElement()->url[0]->loc); + $this->assertEquals('index.html', $service->getXmlElement()->url[1]->loc); + } + + public function testLinksFallbackToRelativeLinksWhenSiteUrlIsLocalhost() + { + config(['hyde.url' => 'http://localhost']); + + $service = new SitemapGenerator(); + $service->generate(); + + $this->assertEquals('404.html', $service->getXmlElement()->url[0]->loc); + $this->assertEquals('index.html', $service->getXmlElement()->url[1]->loc); + } }