How to Add Custom HTTP Headers in Apache?

This guide provides a straightforward walkthrough on how to add custom HTTP response headers in the Apache web server. Managing custom headers is essential for enhancing security, controlling browser caching, and passing necessary metadata to clients. You will learn the prerequisite module required, the basic syntax for the Header directive, and practical configuration examples for your server or .htaccess files.

Prerequisites: Enabling mod_headers

Before you can add custom headers, you must ensure that Apache’s mod_headers module is enabled. Without this module, any header manipulation directives will cause a server error.

The Basic Syntax

To manipulate HTTP headers, Apache utilizes the Header directive. The most common action for adding a new header is set, which replaces any existing header of the same name or creates a new one if it doesn’t exist.

Header set HeaderName "HeaderValue"

Step-by-Step Implementation

You can add custom headers either globally in the main server configuration file, within specific virtual hosts, or locally within a directory using an .htaccess file.

1. Modifying the Configuration File

Open your Apache configuration file (such as httpd.conf, apache2.conf, or your specific virtual host file located in sites-available/).

2. Adding the Directive

Place the Header directive inside the appropriate context. For example, to add a security header and a custom tracking header to a specific virtual host, your configuration block would look like this:

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/html

    # Custom response headers
    Header set X-Custom-Framework "Enterprise-v1"
    Header set X-Content-Type-Options "nosniff"
</VirtualHost>

3. Using .htaccess (Alternative Method)

If you do not have access to the main server configuration files, you can add the rule to an .htaccess file in your website’s root directory:

<IfModule mod_headers.c>
    Header set X-Custom-Header "MyValue"
</IfModule>

Wrapping the directive in <IfModule> prevents your site from crashing if mod_headers is ever disabled.

Testing and Verifying Your Changes

After saving your configuration changes, always test the Apache configuration syntax for errors by running apachectl configtest or apache2ctl -t. If the syntax is valid, restart your Apache service to apply the updates.

You can verify that your custom HTTP response header is active by using a command-line tool like cURL:

curl -I http://localhost

The output will display the HTTP response headers, allowing you to confirm that your new custom header and its corresponding value are being successfully transmitted.