How to inject HTML code into every delivered HTML page?

I've got an Apache web server that delivers static HTML pages. For some reason I can't change the files themselves, but I still want to inject some HTML into every page that is being served.

Is this possible with mod_proxy? If not, could anyone recommend a software that provides such a feature?

EDIT: I have to insert some kind of banner ad (e.g. a javascript) and a tracking pixel.


Solution 1:

You could do this: Work with mod_rewrite to change requests from

/some/static/page.html

to

/htmlinjector.php?url=/some/static/page.html

then use PHP (or whatever you find appropriate) to do the file-manipulation. Add an output cache to improve performance.

As an alternative, Apache Handlers sound helpful:

Modifying static content using a CGI script

The following directives will cause requests for files with the html extension to trigger the launch of the footer.pl CGI script.

Action add-footer /cgi-bin/footer.pl
AddHandler add-footer .html

Then the CGI script is responsible for sending the originally requested document (pointed to by the PATH_TRANSLATED environment variable) and making whatever modifications or additions are desired.

This is more or less what the mod_rewrite approach would do, only with less hackery.

Solution 2:

I am not sure why this hasn't been mentioned in the list of answer. Sorry if it took me 2 years to see this question...

The easiest, most powerful way to do what you want to do what you want is using an Apache filter.

Just have:

ExtFilterDefine css_changer mode=output intype=text/html cmd="/some/php/script.php"
SetOutputFilter css_changer

A possible script:

#!/usr/bin/php
<?

#phpinfo(); // Uncomment to see ALL env variables
$host = $_ENV["HTTP_HOST"]; // www.site.com
$script_name = $_ENV["SCRIPT_NAME"]; // /theme/green/style.css
$pi = pathinfo($script_name);
$type = $pi['extension'];
#print "$host $script  $type";

$stdin = STDIN;

while($line = fgets($stdin)){
  $line = preg_replace('/a/', 'A', $line);

  fwrite(STDOUT, $line);
}
fclose(STDOUT);
?>

This will change all "a"s into "A"s .

Be sure to enable filter in your httpd.conf, like this:

LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so

This question ranks really up in Google and there isn't much out there in terms of forums