feat(seo): add SEO controller for robots.txt and sitemap.xml
- Implemented SeoController with methods for serving robots.txt and sitemap.xml. - Updated robots.txt logic to disallow access to /admin and /api paths. - Enhanced meta tags and Open Graph data in home.html.twig for better SEO. - Added X-Robots-Tag header in SecurityHeadersSubscriber for /admin and /api routes.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Controller;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
class SeoController extends AbstractController
|
||||
{
|
||||
#[Route('/robots.txt', name: 'seo_robots', methods: ['GET'])]
|
||||
public function robots(Request $request): Response
|
||||
{
|
||||
if ($this->isStaging($request)) {
|
||||
$body = "User-agent: *\nDisallow: /\n";
|
||||
} else {
|
||||
$base = $request->getSchemeAndHttpHost();
|
||||
$body = "User-agent: *\n"
|
||||
. "Disallow: /admin\n"
|
||||
. "Disallow: /api\n"
|
||||
. "Allow: /\n\n"
|
||||
. "Sitemap: {$base}/sitemap.xml\n";
|
||||
}
|
||||
|
||||
return new Response($body, Response::HTTP_OK, ['Content-Type' => 'text/plain; charset=UTF-8']);
|
||||
}
|
||||
|
||||
#[Route('/sitemap.xml', name: 'seo_sitemap', methods: ['GET'])]
|
||||
public function sitemap(Request $request): Response
|
||||
{
|
||||
$base = $request->getSchemeAndHttpHost();
|
||||
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n"
|
||||
. '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"
|
||||
. ' <url>' . "\n"
|
||||
. " <loc>{$base}/</loc>\n"
|
||||
. ' <changefreq>weekly</changefreq>' . "\n"
|
||||
. ' <priority>1.0</priority>' . "\n"
|
||||
. ' </url>' . "\n"
|
||||
. '</urlset>' . "\n";
|
||||
|
||||
return new Response($xml, Response::HTTP_OK, ['Content-Type' => 'application/xml; charset=UTF-8']);
|
||||
}
|
||||
|
||||
private function isStaging(Request $request): bool
|
||||
{
|
||||
$host = $request->getHost();
|
||||
|
||||
return str_ends_with($host, '.ddev.site')
|
||||
|| str_contains($host, 'localhost')
|
||||
|| str_starts_with($host, '127.0.0.1');
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,10 @@ class SecurityHeadersSubscriber implements EventSubscriberInterface
|
||||
if (str_starts_with($path, '/api') && !str_starts_with($path, '/api/doc')) {
|
||||
$response->headers->set('Content-Security-Policy', "default-src 'none'");
|
||||
}
|
||||
|
||||
if (str_starts_with($path, '/admin') || str_starts_with($path, '/api')) {
|
||||
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
|
||||
}
|
||||
}
|
||||
|
||||
public static function getSubscribedEvents(): array
|
||||
|
||||
Reference in New Issue
Block a user