Arrow

Apache rewrite rule: conditionally strip HTTP header

First published on March 16, 2015

With mod_headers, you can set, unset, and modify HTTP headers in Apache.

To conditionally set / unset a header, you have to do a bit of a roundabout process and make use of environment variables. In other words, you have to do a test for the condition and set an environment variable based on the result. Then, you can use a RequestHeader directive based on the environment variable.

In this specific example, I wanted to strip an X-Forwarded-Host header only for a specific subdomain. This is because the subdomain was being used to proof the site through a proxy, but I didn’t want the content management system (CMS) behind it to generate links based on the subdomain; I wanted the CMS to generate links based on the normal site domain / URL.

RewriteCond %{HTTP:X-FORWARDED-HOST} proof.yoursite.com [NC]
RewriteRule ^.*$ - [ENV=ISPROOFSITE:true]
RequestHeader unset X-Forwarded-Host env=ISPROOFSITE

You can do something similar with the mod_setenvif Apache module together with the mod_headers module.

SetEnvIf X-Forwarded-Host proof\.yoursite\.com ISPROOFREQUEST
RequestHeader unset X-Forwarded-Host env=ISPROOFSITE

Bonus notes: here’s an example of how to block traffic based on an X-Forwarded-For header. This is useful if you are behind a reverse proxy such as Akamai or Varnish and you cannot block the source IP directly (since the source IP is of the reverse proxy); in these cases, usually you have an X-Forwarded-For or True-Client-IP HTTP header that represents the end client’s IP address.

RewriteCond %{HTTP:X-Forwarded-For}i 123\.127\.77\.38 [OR]
RewriteCond %{HTTP:X-Forwarded-For}i 124\.127\.45\.59 [OR]
RewriteCond %{HTTP:X-Forwarded-For}i 87\.164\.134\.73
RewriteRule ^(.*) - [F]
Arrow

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word