RoyB
RoyB

Reputation: 3164

How can I configure Drupal to send out Last Modified/Etag headers

I am trying to get our Drupal 8.x website to send out ETag headers and/or Last-Modified headers for our pages, so that client browsers (and CloudFlare's intermediary cache) will cache the page. However, when I manually set the ETag headers, they seem to be removed by drupal. I have enabled Drupal's caching mechanism and upped max age to 1 day. Still I never get Drupal to send out these ETag and Last-Modified headers.

Anyone got a hint on where to look at? I cannot find proper documentation on this.

Upvotes: 2

Views: 571

Answers (2)

bdereta
bdereta

Reputation: 913

  1. Create a new module (etag)
  2. Add etag.services.yml
   services:
      etag.response_subscriber:
        class: Drupal\etag\EventSubscriber\ResponseSubscriber
        tags:
          - { name: event_subscriber }
  1. Create ResponseSubscriber class inside modules/custom/etag/src/EventSubscriber/ResponseSubscriber.php
<?php

namespace Drupal\etag\EventSubscriber;

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

class ResponseSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents(): array {
    return [
      KernelEvents::RESPONSE => 'onResponse',
    ];
  }

  /**
   * This method is called whenever the KernelEvents::RESPONSE event is dispatched.
   *
   * @param ResponseEvent $event
   */
  public function onResponse(ResponseEvent $event): void {
    $response = $event->getResponse();
    $etag_value = '"' . md5($response->getContent()) . '"';

    $response->headers->set('ETag', $etag_value);

  }
}

Upvotes: 0

user3037179
user3037179

Reputation: 31

I know this is an old question, but I think it may still be relevant as I've come across this issue in both D7 and and D8. In my investigation and research, I have found these two links addressing this issue in the DO community. Hopefully, it may help someone else.

D8 - https://www.drupal.org/project/lastmodified_since D7 - https://www.drupal.org/project/drupal/issues/3055984

Upvotes: 1

Related Questions