Maybe this exists well documented somewhere – I couldn’t find it. This last month I had to do some work which involved creating an Apache module from scratch. For Linux and MacOSX creating a module is pretty easy – Apache even lends a hand via the APXS tools. On windows there’s a totally different problem. This is why I will try to write here how to create a module.
Hypothesis: We want an Apache 2.x module written in C++ which will respond to certain requests – let’s say .doc files – with a standard text. This is a very easy scenario, but one on which we can build later on.
Part 1 – creating the module on Linux/MacOSX:
This is the easy part. It only takes a few steps to get it done:
- Make sure you have the apache2 and apache2-dev packages installed. On Ubuntu/Debian you can find these packages in the Synaptic Package Manager. On Red Hat / Fedora Core systems you can find rpm’s online. On MacOSX simply install the developer tools.
- Check that you have apxs available. Try typing apxs in a terminal. If the required packages are installed you should get a help page.
- Let’s create the module files. Go to a folder – e.g. /home/my_user and create the enclosing module dir:
$> mkdir modules - Now apxs/apxs2 already comes into play. One of the flags (-g) can generate a default module template. Let’s do this now. Switch folder with the newly created one and call apxs:
$> cd modules
$> apxs2 -g -n doc
or $>apxs -g -n doc - The -n argument sets the newly generated module name, In this case it is mod_doc. The -g tells apxs to create a new template module.
- The default template generates code for a module that implements a custom request handler – just what we need. We could already test the created module and we would get an answer, but it’s not needed right now – it will just print out The sample page from mod_doc. Instead let’s modify the response. Find the line with the above text and change it into whatever you want – let’s say: You are not allowed to download docs! . Save the file and close it.
- Almost there now: we need to turn the .c into an Apache loadable .so. Open a terminal in the modules/doc folder and type:
sudo apxs2 -c -i mod_doc.c - You must use sudo in order for the apxs tool to be able to copy the compiled .so into Apache’s modules folder. If you don’t get an error it’s one step to the finish.
- Let’s tell Apache what to use to handle .doc files. Open httpd.conf (location varies depending on your distro) and add these lines at the end:
LoadModule doc_module modules/mod_doc.so
AddHandler doc .doc - Now restart Apache and request a doc file through the browser. Instead of a download prompt you will get the HTML text added above.
In the next post, Part 2 – modules on Windows with Visual C++ 2005 Express Edition.