How to Check if an HTTP header is Present Using .htaccess

This article describes how you can check with .htaccess rules (in Apache) that a specific HTTP header is present, and deny access if it is not.

The first thing you need to figure out is what the exact name of the HTTP header you want to check for is. Using PHP you can simply make a short script that dumps all headers, so that you can copy and paste the header you’re looking for. Simply create a file called, for example, dumpheaders.php with the following content and visit the page in your browser:

<?php
print_r(getallheaders());

This will list all the request headers that are available to use in your Apache .htaccess file.

For this example, we want to make a rule that says “Check if the CF-Connecting-IP header is present, and return 403 Forbidden if it’s not”.

In .htaccess the HTTP Header you want to reference needs to be prefixed with HTTP: in the rule set.

The first part of the rewrite condition looks for the header variable CF-Connecting-IP which is usually only present if requests come through Cloudflare. Please note that HTTP request headers easily can be spoofed, if these are added from the client side they will just be passed on. This is therefore not a feature you can rely on for security purposes, but can be useful nevertheless.

The second part of the rewrite condition tells what to match. In this case, we want to make an action (rewrite rule) for the case where the header is not present. The second part is a regular expression, where ^ matches the beginning of the match, and $ matches the end. With nothing between ^ and $, that means we are looking for an empty result match telling us that the header is not present.

RewriteCond %{HTTP:CF-Connecting-IP} ^$

The second part of our rule set defines which rule to apply when we have a match. Apache Rewrite rules consist of three parts, where the first defines a pattern, the second a substitution and the optional third defines flags. To deny access based on our condition, we set the pattern to ^ and the substitution to - and set the third parameter to return [F], which in HTTP header language produces the 403 Forbidden header.

# Begin check for Cloudflare-Connecting-IP
RewriteEngine On
RewriteCond %{HTTP:CF-Connecting-IP} ^$
RewriteRule ^ - [F]
# end Cloudflare

The RewriteEngine On directive only needs to be present once in .htaccess, and tells Apache to enable mod_rewrite that allows us to use rewrite rules.

By adding this to the beginning of your .htaccess, you ensure that the rule kicks in before other rules.