Drupalwoo ☉

How to add custom HTTP headers to Drupal responses

HTTP headers control important parts of a Drupal site’s behaviour, from browser caching and content security to cross-origin requests and download handling. A small header can change how a browser stores a page, whether another domain may embed it, or how a reverse proxy treats the response.

Drupal developers often describe this work as adding headers “through a hook”. That is accurate for Drupal 7, where hook_init() and drupal_add_http_header() were available. In modern Drupal, the reliable equivalent is a response event subscriber, because the framework no longer provides a general hook for changing every outgoing response.

The right implementation depends on the Drupal version, the type of response, and whether the header varies by route, user, language, or request. A security header applied globally has different requirements from a cache header added only to an API response.

This guide covers both approaches, with practical module code, caching considerations, testing methods, and deployment details relevant to Australian Drupal sites running behind CDNs or hosting providers.

Why headers belong in the response pipeline

An HTTP response consists of a status code, headers, and a body. Drupal builds the response during routing and rendering, then Symfony’s HTTP kernel sends it to the web server. A response header must be added before that final send operation; changing a rendered Twig template cannot reliably achieve the same result.

Typical examples include X-Content-Type-Options: nosniff, a Content-Security-Policy, a custom X-Site-Environment marker, or a Cache-Control directive. Headers can also describe downloadable files with Content-Disposition or support carefully designed CORS rules for a decoupled frontend.

The location of the code matters. A header added in a controller affects that controller’s response, while a header added during the kernel response event can cover HTML pages, JSON routes, redirects, and other responses. For a site serving customers from Sydney, Melbourne, and Perth, consistent cache and security behaviour is particularly important when a CDN sits between Drupal and the visitor.

Drupal 7 and hook-based headers

Drupal 7 supports a direct hook-based method. A custom module can implement hook_init() and call drupal_add_http_header() for each request:

/**
 * Implements hook_init().
 */
function example_headers_init() {
  drupal_add_http_header('X-Content-Type-Options', 'nosniff');
  drupal_add_http_header('X-Site-Environment', 'production');
}

The module file would be named example_headers.module, with the function prefix matching the machine name. This code runs early in the bootstrap process and is suitable for simple global headers. For route-specific behaviour, inspect the current path before adding the header rather than applying it everywhere.

Drupal 7 sites require extra care with duplicate values. Do not add a header on every execution path if another module, Apache rule, Nginx configuration, or CDN already sets it. For security policies, one contradictory value can make diagnosis difficult. Drupal 7 also reached end of community-supported life, so new security work should include a migration plan rather than extending old patterns indefinitely.

Modern Drupal uses an event subscriber

Drupal 8, 9, 10, and 11 do not provide a general hook_response_alter() implementation. The usual solution is a small custom module containing a service subscribed to KernelEvents::RESPONSE. This is the modern framework-level equivalent of altering the outgoing response.

Create example_headers.info.yml:

name: Example Headers
type: module
description: Adds controlled HTTP response headers.
core_version_requirement: ^10 || ^11
package: Custom

Add the service definition to example_headers.services.yml:

services:
  example_headers.response_subscriber:
    class: Drupal\example_headers\EventSubscriber\ResponseHeaderSubscriber
    tags:
      - { name: event_subscriber }

Then create src/EventSubscriber/ResponseHeaderSubscriber.php:

<?php

namespace Drupal\example_headers\EventSubscriber;

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

final class ResponseHeaderSubscriber implements EventSubscriberInterface {

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

  public function onResponse(ResponseEvent $event): void {
    $response = $event->getResponse();

    $response->headers->set('X-Content-Type-Options', 'nosniff');
    $response->headers->set('X-Site-Environment', 'production');
  }

}

Enable the module and rebuild caches. The subscriber receives a ResponseEvent, obtains the Symfony Response object, and sets headers before the response leaves Drupal. The set() method replaces an existing value, while append() adds another value. Replacement is usually safer for singleton headers such as X-Content-Type-Options.

Building a safe custom module

A response subscriber should be deliberately narrow. Check the route name, request method, response status, or content type when the header applies only to a subset of traffic. For example, an API response may need JSON-specific cache rules, while an administrative page should receive different security restrictions.

use Symfony\Component\HttpKernel\Event\ResponseEvent;

public function onResponse(ResponseEvent $event): void {
  $request = $event->getRequest();
  $response = $event->getResponse();

  if ($request->getMethod() === 'GET'
      && str_starts_with((string) $request->getRequestFormat(), 'json')) {
    $response->headers->set('Cache-Control', 'public, max-age=300');
  }
}

In production code, route checks are often clearer:

if ($request->attributes->get('_route') === 'example.api_items') {
  $response->headers->set('X-Robots-Tag', 'noindex');
}

Avoid placing secrets, internal hostnames, user IDs, or debugging data in custom headers. A header is visible to clients and may be logged by browsers, proxies, monitoring systems, and support tools. During local development, a marker such as X-Drupal-Environment: local can be useful, but it should not identify sensitive infrastructure in a public production response.

Requirement Drupal 7 approach Drupal 10/11 approach Main caution
Global security header hook_init() Response event subscriber Check for server-level duplicates
Route-specific header Inspect the current path Inspect the route attribute Keep conditions explicit
API cache policy Add a header in the hook Set it for matching responses Ensure cache metadata agrees
File download header File delivery callback or hook logic Controller or response subscriber Do not override trusted file responses
Debug marker Temporary hook code Temporary subscriber code Remove before production release

Security headers need deliberate values

X-Content-Type-Options: nosniff is a low-risk baseline for many Drupal sites. Referrer-Policy can reduce the amount of URL information sent to other websites, while Permissions-Policy can disable browser features that a site does not use. These values should reflect the application rather than being copied without testing.

Content Security Policy deserves special attention. A policy such as:

$response->headers->set(
  'Content-Security-Policy',
  "default-src 'self'; img-src 'self' data: https:; script-src 'self'"
);

may break Drupal administration, contributed modules, analytics, embedded maps, or a consent-management tool. Start with Content-Security-Policy-Report-Only, review browser reports, and then tighten the policy in stages. Inline JavaScript generated by themes and modules is a common reason a copied policy fails.

CORS headers require the same discipline. Never combine Access-Control-Allow-Origin: * with credentials, and do not reflect the incoming Origin header without validating it against an allowlist. A Drupal JSON endpoint used by a React application hosted in Brisbane may need a specific origin, while a public, unauthenticated feed might need no CORS header at all.

Caching, variations, and proxy behaviour

A response header can change caching even when the page body remains identical. Cache-Control, Vary, ETag, and Last-Modified must describe the actual response. If a header changes according to language, cookie, role, or origin, the cache needs a corresponding variation strategy.

For example, adding Access-Control-Allow-Origin based on the request origin without setting Vary: Origin can cause a shared cache to serve the first origin’s header to later visitors. Similarly, a response that varies by a session cookie should not receive a broad public cache directive. Drupal’s cache metadata and the infrastructure cache must agree.

This is especially important for Australian stores using a global CDN. A visitor in Perth may receive a cached object created by a request from Melbourne, while the origin server may sit in Sydney or overseas. Test through the actual CDN hostname and inspect headers after cache warming. Purging Drupal’s cache alone may not remove an already stored edge response.

If the header is a fixed security value, it normally does not need a cache context. If it depends on request data, investigate whether the response should be varied, made private, or excluded from caching. A five-minute API cache may be appropriate for public stock information, but not for account details or personalised pricing.

Testing and debugging the final response

Clear Drupal caches after enabling a module or changing its service definition:

drush cr

Then inspect the complete response with command-line tools:

curl -I https://www.example.com/
curl -sS -D - -o /dev/null https://www.example.com/api/items

Use -L when redirects are involved, because a header on the redirect response may differ from the header on the final page. Test anonymous and authenticated requests, HTML and JSON routes, successful and error responses, and both HTTP and HTTPS entry points. Browser developer tools are useful for confirming what the browser received, while curl helps avoid extensions and browser caching.

When a header is missing, check module status, namespace spelling, service YAML indentation, and the actual route being requested. The Drupal container must be rebuilt after service changes. For deeper investigation, the Drupal Xdebug and logs guide can help trace execution and identify whether the subscriber ran.

External header inspection can reveal CDN or web-server changes that are invisible inside Drupal. A practical HTTP testing reference can complement local curl checks, especially when validating redirects, TLS termination, and responses from a public Australian domain.

Deployment patterns for Australian sites

Keep application-owned headers in a custom module and infrastructure-owned headers in the web server or CDN, with one clear source of truth. For example, a Content Security Policy might be maintained in Drupal because it changes with modules, while HSTS may be managed centrally after the entire domain and its subdomains are ready for HTTPS.

Coordinate deployments around Australian business hours when a header can affect checkout, customer portals, or marketing integrations. A change made late on a Friday afternoon in AEST can still be serving cached responses in other time zones, and a Perth-based team may see different edge behaviour from a test performed against an origin server in Sydney.

Before release, record expected values for the homepage, administration route, API endpoint, login form, redirect, and 404 response. Check the site through its normal .au hostname, its CDN, and any alternate load-balanced origin. If the project uses NBN-connected office testing, repeat important checks from a mobile connection because local DNS, proxy, and ISP caching can hide production problems.

Custom HTTP headers are small pieces of code with system-wide effects. A version-aware implementation, explicit route conditions, cache-aware values, and tests at the public edge make them predictable across Drupal responses, browsers, and hosting infrastructure.