< DirectoryMatch > and regular expressions


ApacheServers

I learned something new in Apache today that I thought I’d share with the group. You may already know this but always good to write stuff down.

I’m maintaining an application on a virtual host that uses a vhost.conf file to set php settings (such as auto_prepend_file, open_basedir, and include_path) for the application (rather than using individual .htaccess files). Initially we were setting the same settings for the entire application, and so we could use the Directory container in the vhost.conf file like this:

< Directory
/path/to/public/directory >

php_value auto_prepend_file /path/to/
global/configuration/config.php

< /Directory>

And then that file would be automatically prepended to every file in the app, so stuff like database settings were always available. But we’re integrating a second module that will need it’s own configuration files so I was trying to find a way to have the initial include work recursively for every directory *except* the new integrated directory. In short, I wanted: /path/to/public/directory/EXCEPT_FOR_NEW_DIRECTORY.

I learned that to do that you have to use < DirectoryMatch > and feed it a regular expression. You could also feed a regular expression to < Directory > but < DirectoryMatch > is intended for that purpose. It was a little more complicated than I’d thought to write the regex, since you can’t just write a regex that excludes an entire word — those end up searching for each character in the word, so if your word is [myword] your regex works on m,y,w,o,r,d — which is not what you want. I found an example that will check for the first three letters of a word (since I knew that would be enough for me, and b/c it was getting long) and tailored that to my purposes. I also found one for negative lookbacks, but that was more complex than I needed.

So I ended up doing this:

< DirectoryMatch
"/usr/local/psa/home/vhosts/mecme.org/httpdocs/
(cm[^e]|c[^m]e|c[^m][^e]|[^c]me|
[^c]m[^e]|[^c][^m]e|[^c][^m][^e])(w*)" >

-- do stuff

< / DirectoryMatch>

And then I had another simple < Directory > container for the included module.

***

Later it was pointed out to me that “if it’s only some options you don’t want you could subtract them:”

< Directory
/usr/local/psa/home/vhosts/mecme.org/httpdocs >

Options Indexes

< /Directory >

< Directory
/usr/local/psa/home/vhosts/
mecme.org/httpdocs/different_dir >

Options -Indexes +ExecCGI

< /Directory>

I don’t know a ton about apache configuration, so I went with my first method, which was working. If anyone can chime in and further explain the latter example with the subtraction, that’d be great.