Skip to content

Commit

Permalink
Merge pull request #783 from City-of-Helsinki/UHF-10255-add-module-fo…
Browse files Browse the repository at this point in the history
…r-robots-header

UHF-10255: Add module for X-Robots-Tag handling if helfi_proxy can't be used
  • Loading branch information
juho-lehmonen authored Jun 28, 2024
2 parents 6827071 + a225bb6 commit 758958e
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
8 changes: 8 additions & 0 deletions modules/helfi_robots_header/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Helfi Robots Header

Handles robots-tag header if `helfi_proxy` module can't be installed.

This module adds `X-Robots-Tag: noindex, nofollow` to all page responses if `DRUPAL_X_ROBOTS_TAG_HEADER` if set to 1.

**NOTE:** Because this duplicates some functionality from `helfi_proxy` module, both modules should not be enabled at the same time.

5 changes: 5 additions & 0 deletions modules/helfi_robots_header/helfi_robots_header.info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: 'HELfi Robots headers'
type: module
description: Adds noindex and nofollow robots tags to headers.
package: Custom
core_version_requirement: ^9 || ^10
4 changes: 4 additions & 0 deletions modules/helfi_robots_header/helfi_robots_header.services.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
services:
Drupal\helfi_robots_header\EventSubscriber\RobotsResponseSubscriber:
tags:
- { name: event_subscriber }
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Drupal\helfi_robots_header\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
* Adds an X-Robots-Tag to response headers.
*/
final class RobotsResponseSubscriber implements EventSubscriberInterface {

public const X_ROBOTS_TAG_HEADER_NAME = 'DRUPAL_X_ROBOTS_TAG_HEADER';

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() : array {
$events[KernelEvents::RESPONSE][] = ['onResponse', -100];
return $events;
}

/**
* Adds an X-Robots-Tag response header.
*
* @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
* The event to respond to.
*/
public function onResponse(ResponseEvent $event) : void {
$response = $event->getResponse();

if ((bool) getenv(self::X_ROBOTS_TAG_HEADER_NAME)) {
$response->headers->add(['X-Robots-Tag' => 'noindex, nofollow']);
}
}

}

0 comments on commit 758958e

Please sign in to comment.