How to host several websites in Ubuntu localhost

How to create virtual hosts in ubuntu

You can hosts several websites in Ubuntu and the following articles describe how to do that.
We are going to use the terminal to do this. Open the terminal and ensure you have logged in as root.

Change your directory to www folder by typing:

# cd /var/www/

We are going to create a local website that we will access with URL example4.com.

Make a directory example4.com by typing:

# mkdir example4.com

Change your directory to example4.com directory by typing:

# cd example4.com

We are going to create a public_html folder where our index.php file will be located: Type

# mkdir public_html

We will create a new file inside the folder by using vim. If you do not have vim you can install it by typing sudo apt-get install vim or use the default nano. To create the index.php file type:

#vim index.php

Once it open press I to insert mode and write the following PHP code:

<?php
echo "Welcome to example4.com local website";
?>

After that, press Escape key to get out of insert mode then full-colon (:) then type wq! for write and quit. Now we have already set out the directory in the www folder.

We are now going to enable our site in apache and to do this we will change our directory to apache hence type:

# cd /etc/apache2/sites-available

We are going to copy the content of the default file (type ls to list the files in that particular folder) 000-default.conf. Type the following:

cp 000-default.conf example4.com.conf

We are now going to edit our new file example4.com.conf.

The default file has the following files (The ones starting with # are comments)

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Edit your new file example4.com.conf to look like

ServerAdmin webmaster@example4.com
ServerName example4.com
ServerAlias www.example4.com
DocumentRoot /var/www/example4.com/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

We are going to enable our site by typing:

# a2ensite example4.com.conf

Then restart the apache by typing:

# service apache2 reload

We are then going to add our site in the hosts file. To open the file just type

#vim /etc/hosts

Add your site name with the local host IP 127.0.0.1

example4.com 127.0.0.1

You can restart your apache again.

Now go to your browser and access your website using the URL example4.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »