Virtual Hosts on Ubuntu 18.04

As a developer, we are always creating folders for various projects, which can then be accessed by prepending

http://localhost or http://127.0.0.1

to the folder name of the project. Would it not be nicer if we could access it using the real domain name, with the tld replaced by, say, local or dev. For example,

www.helloworld.com will be www.helloworld.local

While this might seems a bit daunting, this can be achieved in just a few steps. Let’s get started.

Install apache, if it is not already installed

$ sudo apt-get install apache2

Check if apache has been installed successfully by opening the following in your browser:

http://localhost or http://127.0.0.1

You should see a page like in the screenshot below:


Apache’s public folder is located at /var/www/html/ and this is where you would place the files for your project.

Let’s call our project technogeek.

We shall create a folder inside the public folder by entering the following command:

$ sudo mkdir /var/www/html/technogeek

This newly created folder is owned by root, so we need to change to a regular user
$ sudo chown -R $USER:$USER /var/www/html/technogeek $ sudo chmod -R 755 /var/www/html

Create the conf file
$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/technogeek.local.conf

Now edit the conf file to match your project
$ sudo nano /etc/apache2/sites-available/technogeek.local.conf

The important sections to edit are:

ServerAdmin webmaster@technogeek.local
ServerName technogeek.local
ServerAlias www.technogeek.local
DocumentRoot /var/www/html/technogeek

Enable the virtual host you have created
$ sudo a2ensite tehcnogeek.local.conf

Restart apache for the virtual host created comes into life.
$ sudo systemctl restart apache2

Last step is to point the local domain to your computer’s ip.
$ sudo nano /etc/hosts

Add a new line like

127.0.0.1 technogeek.local
127.0.0.1 www.technogeek.local

Save and exit. You can now access your project by entering the following in your browser’s address bar: http://technogeek.local

That’s it. I hope you enjoyed it.

2 Comments

  1. Thank you. I think its worth mentioning that the folder structure might be different on different distros. In your tutorial it looks like Ubuntu but on Debian or CentOS it looks different

    • Hi @John,
      Thanks for the point. In fact I did refer only to Ubuntu folder structure and was planning to update this article regarding other distros. Unfortunately had personal issues and was a bit disconnected.

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.