Is there a way to check if a directory exists in Apache configuration files?

Viewed 5602

Is there a way to include configuration settings in Apache based on if a directory exists? Basically I have a portable hard drive that I transport between work and home that has some stuff I'm developing on it. I only want the Apache config to load a particular virtual host if the folder exists.

4 Answers

Since Apache 2.4.34 you can now use <IfFile>...</IfFile> which will check to see if a file exists. There's more details on the <IfFile> page.

I've come up with a solution that seems to work for Linux and OS X, and it hinges on "mountpoints". It might be possible to emulate it within Windows, as well, but you would probably have to get creative with FUSE and/or Cygwin.

If you create an empty folder in your home directory, such as "/Users/username/ExtraVhosts", you can add an apache directive to "Include /Users/username/ExtraVhosts/*".

Then, when you insert your thumb drive, you can mount somewhere and then use mountpoint "binding" to cross-link the ExtraVhosts folder to a folder on the mobile device.

An OS X example:

  • I have a thumb drive called 'Cherrybomb'
  • When I insert it, it always gets mounted to /Volumes/Cherrybomb
  • I can then use bindfs (sudo port install bindfs) to mount a subfolder of it, like so:
    • sudo bindfs /Volumes/Cherrybomb/Projects/vhosts /Users/username/ExtraVhosts
  • Then I can restart apache to read in the updated configuration:
    • sudo /opt/local/apache2/bin/apachectl restart

At that point, it's just a matter of adding entries in /etc/hosts for server aliases to get picked up.

The linux equivalent would be using the "--bind" parameter of the mount command.

One caveat: This makes it difficult to quickly unmount the USB drive, since it is always marked as "in use" by apache. Here's a removal procedure:

  • Close all open files and terminal sessions that are using the drive (the present-working-directory in terminal can cause unmount issues)
  • Stop apache: sudo /opt/local/apache2/bin/apachectl stop
  • umount /Users/username/ExtraVhosts

Then you can either unmount it graphically or manually (umount /Volumes/Cherrybomb).

If your work and home machines mount the drive to different locations, you could have multiple vhosts folders - home_vhost, work_vhost, etc - and use that in the binding step.

I hope this helps someone out :)

Related