Http substitutions filter : multiple filters with regex on response bodies
nginx_substitutions_filter is a filter module which can do both regular expression and fixed string substitutions on response bodies. This module is quite different from the Nginx's native Substitution Module. It scans the output chains buffer and matches string line by line, just like Apache's mod_substitute.
I've played with classic substitution module but due to limitations (only one pattern, no regex), it wasn't easy to do all I wanted to do. That's why I've searched a better module and to add it on my Debian server. Unfortunately, it's not currently available in Nginx packages on Debian. That's why I needed to create new packages with it built in.
To get a quick understand of what this module is able to do, we're going to take an example. Let's say we need to add a CSS style on every pages on our website. You've got multiple solution to do it and most of them need to modify the application code. The problem is, each time you will get an application upgrade, you'll need to think about this modifications. The other solution (if possible) is to create an extension for you application, but it's boring to manage.
With that solution, you can change the end of the head banner and add any style or JS that you want. It works with everything in fact. As described, it's a string replacement solution. This extension is really powerfull. I'll explain in the next days how I use it for my own usage.
We first need to download package source and install all dependencies to recompile Nginx :
mkdir ~/nginx_new ; cd ~/nginx_new aptitude install devscripts dch apt-get build-dep nginx-extras apt-get source nginx-extras
As I use nginx-extras package, I take this one but you can take only nginx if you want.
Now let's get sources from the official site :
cd ~/nginx_new/nginx-1.2.1/debian/modules/ git clone git://github.com/yaoweibin/ngx_http_substitutions_filter_module.git
Then add this line to make it compiled on the next step :
dch -l local 'New version with nginx_substitutions_filter included'
Now you're ready to compile and package it automatically :
cd ../.. debuild -us -uc
Now it's easy, let's install :
cd ~/nginx_new dpkg -i nginx-extras_1.2.1-2.2local1_amd64.deb nginx-common_1.2.1-2.2local1_all.deb
Let's take the default configuration for instance and then add to your location this kind of string replacements :
As you can see, regex works and simple remplacement strings works as well.