Creating a SubDomain in Apache

I recently needed to create a subDomain for one of my websites. This subdomain points to a separate WordPress installation that is linked to from the parent domain. Here’s a quick overview of how to do this.

The directory structure on my server is similar to the following:

var/www/html/example
var/www/html/blog

Start by navigating to the /etc/apache2/sites-available directory, then create a configuration file for the new subDomain using a command structured as follows – just switch ‘example’ and ‘blog’ with your target domain and subDomain names:

$ sudo cp 000-default blog.example.com.conf

Now open blog.example.com.conf in an editor and make the following changes:

ServerName blog.example.com
ServerAdmin <your admin's email address goes here>
DocumentRoot /var/www/html/blog

If it’s been set, remove or comment out ServerAlias.

Next, enable the new subDomain as follows:

sudo a2ensite blog.example.com.conf

Now reload and restart the server:

$ sudo service reload apache2
$ sudo service restart apache2

And finally, set up a CNAME record for the subdomain in the parent domain’s DNS zone file.

That’s all! Go to blog.example.html to view the contents of the subdirectory.