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/mod_rewrite.so
LoadModule headers_module modules/mod_headers.so

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/printenv.pl/foo/bar
RewriteRule ^/([^/]+)/([^/]+) /cgi-bin/printenv.pl/$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 http://server.com/foo/bar would be rewritten to http://server.com/cgi-bin/printenv.pl/foo/bar and if you inspect the HTTP headers during printenv.pl 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