This guide will show you how to create a simple module to capture the CF-IPCountry
header incoming from Cloudflare (https://support.cloudflare.com/hc/en-us/articles/200168236-Configuring-Cloudflare-IP-Geolocation) and set it to the response headers using an Event Subscriber. You can then follow up with article Using custom Vary headers to create variations in Varnish cache to vary cache on CF-IPCountry
.
Create a custom module using the following structure replacing cf_header
and CfSubscriber
with the names of your choice:
Edit the CfSubscriber.php
file to contain the below, modifying the namespace and class name appropriately:
<?php
namespace Drupal\cf_header\EventSubscriber; #<-- MODIFY THIS
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class CfSubscriber. <-- MODIFY THIS
*/
class CfSubscriber implements EventSubscriberInterface { #<-- MODIFY THIS
/**
* Symfony\Component\HttpFoundation\RequestStack definition.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a new CfSubscriber object. <-- MODIFY THIS
*
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events['kernel.response'] = ['kernelResponse'];
return $events;
}
/**
* This method is called when the kernel.response is dispatched.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The dispatched event.
*/
public function kernelResponse(FilterResponseEvent $event) {
$request = $this->requestStack->getCurrentRequest();
$headers = $request->headers->get('CF-IPCountry');
$response = $event->getResponse();
$response->headers->set('CF-IPCountry', $headers);
}
}
Edit cf_header.services.yaml
to contain the below, modifying service name and class name appropriately:
services:
cf_header.default: # <-- MODIFY THIS
class: Drupal\cf_header\EventSubscriber\CfSubscriber # <-- MODIFY THIS
arguments: ['@request_stack']
tags:
- { name: event_subscriber }
You can now enable the module on your site which will capture the request header header and set it to the response.