How to create apache virtual hosts in apache2(Ubuntu)

The layout of apache configurations in rehat distros and debian distros are entirely different. I’m here explaining how to create a virtual host in ubuntu.

In your home directory create a ‘public_html’ folder and create sub directories as follows.

mkdir -p public_html/domain.com/{public,private,log,cgi-bin,backup}

And then create a sample test.html file in public_html directory. Make sure that the public_html directory has be read and executable permissions.

Now we need to add virtual host entry in sites-available directory.

nano /etc/apache2/sites-available/domain.com

# domain: domain.com
# public: /home/demo/public_html/domain.com/

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@domain.com
  ServerName  www.domain.com
  ServerAlias domain.com

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html
  DocumentRoot /home/demo/public_html/domain.com/public

  # Custom log file locations
  LogLevel warn
  ErrorLog  /home/demo/public_html/domain.com/log/error.log
  CustomLog /home/demo/public_html/domain.com/log/access.log combined

</VirtualHost>

 

Now we need to enable the site.

a2ensite domain.com

Then restart the apache

/etc/init.d/apache2 reload

If you are creating this in your local machine add appropriate entry in /etc/hosts file

nano /etc/hosts
127.0.0.1 localhost
127.0.1.1 domain.com

 

Then navigate to domain.com/test it will show the test file contents.<!> And your virtual host is working fine.