Setting up a wildcard Apache virtual host for your local WordPress development

While setting up the environment for a new web project, developers often tend to create a virtual host for local development. Here is how someone can set up an Apache virtual host for a given WordPress installation that resides in the folder named grantchester within Apache webroot directory (in case you are using Apache). In my case, the virtual host will have the hostname of grantchester.dev. As you can see, the hostname consists of main domain (grantchester) and the TLD (.dev, the very last segment of a valid domain name).

<VirtualHost *:80>

ServerName grantchester.dev

ServerAdmin [email protected]

DocumentRoot /home/itobuz-06/dev/grantchester/public

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Then you have to map grantchester.dev to your loopback ip 127.0.0.1 in the host file of your system sans the protocol.

Now I am going to show you how you can create a “catchall/wildcard” virtual host that will work with only top-level domain .dev on the local environment and will map the primary domain to each valid WordPress documentroot directory automatically without you having to create a virtual host entry in one of the Apache’s site config files.

We would be using the ServerAlias directive of Apache. For that to work, you have to enable Apache’s vhost_alias module. Run this command from the terminal.

sudo a2enmod vhost_alias

Create /etc/apache2/sites-available/catchall.conf with the following content.

<VirtualHost *:80>
ServerAlias localhost *.dev #wildcard catch all
VirtualDocumentRoot /var/www/html/%1
UseCanonicalName Off
     <Directory “/var/www/html”>
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          Allow from all
          Require all granted
    </Directory>
</VirtualHost>

Enable the virtual host configuration: sudo a2ensite /etc/apache2/sites-available/catchall.conf

Then reload Apache configuration: sudo service apache2 reload

You may need to restart apache also.

Then you will just need to create an entry in the host’s file for the new WordPress setup.

127.0.0.1<tab>grantchester.dev.