Enabling UserDir on only one Apache VirtualHost

Let’s say you have a web server running apache and you have a bunch of virtual hosts for a bunch of domains. You want to enable UserDir so that example.com/~user URLs automatically map to (by default) the public_html directory in each user’s home directory. Apache already includes a userdir module, so you go and enable it. But, oops, by default it enables it on all your hosts, not just one. You want it enabled on just one, not all of them. So you go and google and there are a bunch of complicated solutions to this that seem way too much like overkill. Fortunately there is a much simpler solution:

First, go to your apache configuration directory, for example on Debian:

cd /etc/apache2

Second, enable the userdir module:

sudo a2enmod userdir

Third, delete the enabled userdir configuration file:

sudo rm mods-enabled/userdir.conf

Fourth, edit the virtual host configuration file, e.g. sites-enabled/example.com.conf, that you want to use userdir on and add this line within the VirtualHost scope:

Include mods-available/userdir.conf

Fifth, reload apache, usually by running (if you use systemd):

sudo systemctl reload apache2

Really simple, right? An explanation of this is in order: Why did we enable it only to delete the configuration? Enabling a module actually does two things: First it adds a .conf file that tells apache the default configuration of the module. Second it adds a .load file that tells apache to load a dynamic library with the executable code that apache runs when the module is used.

By default, the .conf file applies globally, i.e. to all of the sites in use. This is great if you want all of your sites to do the same thing. It’s not so great if you want the module enabled only on one or a few sites. The effect of the above is to load the dynamic library so that apache can use it, but not to add the global configuration. The “Include” in the virtual host configuration file will enable the configuration for the module for that virtual host only.

If you need to further tweak things (enable or disable specific usernames, the path, etc.) then instead of using “Include” you can copy the contents of mods-available/userdir.conf into your virtual host configuration file and customize as needed.

In principle, the same procedure should work for other modules you want to use only on specific virtual hosts.