How to create Virtual Hosts on Ubuntu?

Create the directory for example.com as follows, using the -p flag to create any necessary parent directories:

sudo mkdir -p /var/www/example.com

Next, assign ownership of the directory with the $USER environmental variable:

sudo chown -R $USER:$USER /var/www/example.com

The permissions of your web roots should be correct if you haven't modified your unmask value, but you can make sure by typing:

sudo chmod -R 755 /var/www/example.com

Next, create a sample index.html page using nano or your favorite editor:

nano /var/www/example.com/index.html

Inside, add the following sample HTML:

<html>

    <head>

        <title>Welcome to Example.com!</title>

    </head>

    <body>

        <h1>Success!  The example.com server block is working!</h1>

    </body>

</html>

Save and close the file when you are finished.

In order for Apache to serve this content, it's necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf directly, let's make a new one at /etc/apache2/sites-available/example.com.conf:

sudo nano /etc/apache2/sites-available/example.com.conf

Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

	
<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save and close the file when you are finished.

Let's enable the file with the a2ensite tool:

sudo a2ensite example.com.conf

Disable the default site defined in 000-default.conf:

sudo a2dissite 000-default.conf

Next, let's test for configuration errors:

sudo apache2ctl configtest

Restart Apache to implement your changes:

sudo systemctl restart apache2