Thursday, October 14, 2010

On the fly subsitution of text with mod_substitute under apache httpd 2.2.x

Got a request to insert a javascript snippet on every webpage just before the closing body tag.

The brute-force approach is obvious, manually adding the snippet on each and every webpage manually. This can be automated by writing a perl script or vi script.

Another approach is to use mod_substitute in apache 2.2 (since 2.2.7) which can substitute text in the response on the fly. This can be combined with mod_cache and mod_proxy.


LoadModule substitute_module modules/mod_substitute.so

<location / >
AddOutputFilterByType SUBSTITUTE text/html
Substitute "s|</body>|<script type="text/javascript" src="your code"></script></body>|ni"
</location>


Note, regular expression can be used, and the separator does not necessarily be the slash - "/",
in the above example, pipe character - "|" is used. Since there are whitespaces in the expression, the whole string has to be enclose in double quote '"' and so the double quote character '"' in the expression has to be escape i.e. '\"'

Voila! Every html served via the webserver got inserted with the snippet. In combination with mod_cache, the substituted result can be cached.

http://httpd.apache.org/docs/2.2/mod/mod_substitute.html

1 comment:

gt said...

I have a question about mod_substitute : Is it possible to make use of this filter to substitute value that will be known only at run-time for words that match a pattern ?