In this tutorial I will show you how to configure a single Apache 2 web server to run multiple websites (virtual hosts) on Ubuntu 16.04 LTS
Sometimes you may want to point different domains to a single web hosting. This is price effective and may be done with a simple configuration. All you need is a root access to your Ubuntu server.
Pre-requirements
This tutorial assumes you already have Apache 2 up and running on your linux host. Also the tutorial shows how to set up different MySQL users for your sites, so if you want to go with this step, MySQL should be also installed on your server.
Point the Domain
What you need to do first is point your domain for example https://javatutorial.net to your web-server IP address.
- Find out your server’s public IP address with following command
curl ipinfo.io/ip
- Log in to your domain provider (for example GoDaddy, or whatever service you used to register your domain)
- Go to DNS and change the A Record to point to your server IP
I listed this step as #1, because DNS refresh may take hours or days. Be patient and don’t expect your domain to be redirected instantly.
Create the Directory Structure and User Permissions
By default your web server has a single root directory for your website, which is /var/www/html/
. We are going to change this and create separate folders for each website we want to add. For example /var/www/javatutorial
Make separate folder
sudo mkdir /var/www/javatutorial
Give ownership of the directory to the Apache web user (which is www-data)
sudo chown YOUR_USER_NAME_HERE:www-data -R /var/www/javatutorial
add your username to the web group
sudo usermod -aG www-data YOUR_USER_NAME_HERE
Add Virtual Hosts to Apache
Go to Apache’s configuration folder /etc/apache2/sites-available
and make a new file named
javatutorial.conf
Edit the content of javatutorial.conf
<VirtualHost *:80> ServerAdmin admin@javatutorial.net ServerName javatutorial.net ServerAlias www.javatutorial.net DocumentRoot /var/www/javatutorial ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
Enable the new configuration
sudo a2ensite javatutorial.conf
Reload Apache to activate the new configuration
service apache2 reload
Create MySQL Database and User for the New Site
We will create a new MySQL database and user and following credentials:
- Database name: javatut
- Database user: tutuser
- User password: tutpass123
Log in to MySQL as root
mysql -u root -p
Now we create the new database and user. Set a password to the user and grant privileges for this new user to use the database
mysql> CREATE DATABASE javatut; mysql> CREATE USER tutuser@localhost; mysql> SET PASSWORD FOR dbuser@localhost= PASSWORD("tutpass123"); mysql> GRANT ALL PRIVILEGES ON javatut.* TO tutuser@localhost IDENTIFIED BY 'tutpass123'; mysql> FLUSH PRIVILEGES;