May 18 2012

mod_rewrite and mod_headers to rewrite headers

This came up at work today and I don’t see a solution anywhere out there: how can you use Apache’s mod_rewrite to add, modify or delete HTTP headers? After a bit of testing I came up with this:

LoadModule rewrite_module modules/
LoadModule headers_module modules/

RewriteEngine On

# all /foo/bar urls set env vars FIRST=foo and SECOND=bar
RewriteRule ^/([^/]+)/([^/]+) - [E=FIRST:$1,E=SECOND:$2]

# rewrite all /foo/bar to /cgi-bin/
RewriteRule ^/([^/]+)/([^/]+) /cgi-bin/$1/$2 [PT]

# if env var FIRST is set then create header First: $ENV{FIRST}
RequestHeader set First %{FIRST}e env=FIRST

# if env var SECOND is set then create header Second: $ENV{SECOND}
RequestHeader set Second %{SECOND}e env=SECOND

Using this, any URL of the form would be rewritten to and if you inspect the HTTP headers during you would find the headers "First: foo" and "Second: bar". Hope somebody else finds it useful.

2 Responses to “mod_rewrite and mod_headers to rewrite headers”

Leave a Reply