Bash – Apache – add http headers to requests, using script (bash, perl, php etc) to set the headers

apache-2.2bash

I trying to work out the feasibility of a project where I want to be able to have a script run on every request (preferably filtered by mime type), and a script run to set the headers for the response.

Basically I want requests for text/html and application/json documents to have http headers with arbitrary data generated by the system (the actual headers added will be git branch and commit hash info).

This is for local and staging webservers, so performance impact isn't a high concern.

I have investigated mod_ext_filter with bash scripts, and while I could successfully inject strings into the output, I couldn't access the headers (I assume they have already been sent?)

Are there any other options I can investigate?

My attempt so far (in vhost):

    ExtFilterDefine githeaders mode=output \
                   cmd="/bin/bash /path/to/script/git_headers.sh" preservescontentlength

   <Location />
     SetOutputFilter githeaders
   </Location>

Basic bash script testing echo

#!/bin/bash

echo "hello"

cat

The above works fine, injecting hello into the responses, but I can't work out how to alter headers. Any help/suggestions appreciated.

Best Answer

The examples I have seen typically use mod_headers to insert, remove or replace headers, like the example below from the manual.

# mod_ext_filter directive to define the external filter
ExtFilterDefine gzip mode=output cmd=/bin/gzip

<Location /gzipped>
# core directive to cause the gzip filter to be
# run on output
SetOutputFilter gzip

# mod_header directive to add
# "Content-Encoding: gzip" header field
Header set Content-Encoding gzip
</Location>

I can only assume that using the regular API and by writing the filter in C you get more access and will be able to modify headers.

Related Topic