How to Setup Virtual Hosts in Ubuntu

How to Setup Virtual Hosts in Ubuntu

Here are the simple steps to make virtual hosts on Apache in Ubuntu OS.

For example purpose, I am assuming that you are going to create a virtual host for “xyz.com”.

Let’s began. The first thing that you need to create a directory to hold and serve project files.

   sudo mkdir -p /var/www/xyz.com/html

Now give permissions to it. the above directory is owned by root user now. We should change the ownership of this directory to the regular user.

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

The “$USER” variable indicates the currently logged in user. Set the read permissions to the webroot (/var/www/xyz.com/html) directory, so that everyone can read files from that directory.

sudo chmod -R 755 /var/www/pravih.com/html

Now clone the default Apache configuration and create xyz.com.conf file.

$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/xyz.com.conf

Open the new configuration file and update the values for the ServerName, ServerAlias, and DocumentRoot. Where ServerName is the virtual hostname and the ServerAlias is the www version. The DocumentRoot is the absolute path to the directory where your project is stored.

<VirtualHost *:80>
        ServerName xyz.com
        ServerAlias www.xyz.com
 
        ServerAdmin webmaster@xyz.com
        DocumentRoot /var/www/xyz.com/html
</VirtualHost>

Next, enable the new virtual host configuration. If you want to disable virtual host configuration use a2dissite instead of a2ensite.

$ sudo a2ensite xyz.com.conf

Lastly, add it to the hosts file.

$  sudo nano /etc/hosts

And add the virtual host domains one by one as shown below.

127.0.0.1 xyz.com
127.0.0.1 www.xyz.com

Last step but very important step restart Apache.

$ sudo service apache2 restart

Share This Blog

Comment

Do you want to get our quality service for your business?