Code, Computers & Random Junk

Macros in Apache

In Apache 2.4 you’ll find Macros. They are really useful and saves a lot of code. It’s like callable “snippets” you inlcude later where you want them.

Since I have a server setup with dual versions of PHP and work with a number of VirtualHosts running different versions &/or both versions (on different ports), It’s really useful. Especially when combining them with defined variables (also new in 2.4).


To create a macro it’s a little bit like a function where you can pass in variables.

So if using an example like:

<Macro Foo $bar>

    // a lot of code where you can use ${bar}


To use it in your virtualhost (or where ever you want to call it).

Use Foo MyBarValue

A good practice is to unset it when it’s been used - after the last one.

UndefMacro Foo

I inlcude the file with my macros (before the VirtualHosts) and then undefine each macro in httpd.conf after all included files that use the macros.

Include conf/other/httpd-macros.conf

Include conf/extra/httpd-vhosts.conf

UndefMacro Foo
UndefMacro Bar
UndefMacro Baz

Apache’s documentation on Macros.


Also really useful and you can set a variable name and use it where ever you want/need.

# Define <name> <value>
Define server_name foobar.baz

In VirtualHost I can use that example like:

<VirtualHost *:80>
    Define server_name foobar.baz

    ServerName ${server_name}
    ServerAlias www.${server_name}
    ServerAdmin admin@${server_name}

    DocumentRoot /srv/www/${server_name}/public_html/

    // Logs with ${server_name}

    <Directory "/srv/www/${server_name}/public_html/">
        Options -Indexes +SymlinkIfOwnerMatch
        Require host localhost
        Require ip 127
        Require ip ::1
        // etc

For next VirtualHost it’s just to copy/paste and change: foobar.baz. Of course one could make a more efficiant solution with a template like file for all, but in my case where I use different versions of PHP and also have a couple of different locations where my VirtualHosts live I keep separate file for each and to control the php version, what port etc. And then I use the Macros to include either the php as a module or the Macro with the code for FastCGI.

It’s only my dev/test-server so it’s not too important to make it “perfect”.

Apache’s documentation on Define.


Ok, so to put both Define and Macro in a combined example…

Since I’ve defined a name for my server I can use that variable in the Macro. The Macro might look something like:

<Macro FastPHP ${sockname}>
    // All the FastCGI related stuff
    // ...where I make use of ${sockname}

In my VirtualHost I can just add:

#Use ModPHP
Use FastPHP ${server_name} // defined eralier in the top of the Virtualhost

I can the make use of that name inside the FastCGI setup for the name and socket etc

I’ll write more about the setup I use in another post… But here, as a “model”, it shows how really great and useful it is.