Instead of a single domain per web server , it is possible to set up multiple domains or hosts in a single server . This technique is called Virtual Hosts. You can implement virtual host in any of the operating systems or any web server.
In this article, ,we will be discussing on creating virtual host Apache in Ubuntu
Virtual Hosts
A virtual host is a method that can be used to host multiple domains (or websites) on a single physical server or machine. Instead of requiring a separate server (i.e. OS or a Web Server )or each website, a single server can host multiple websites by utilizing a feature called virtual hosts. Virtual hosts can be configured in most of the web servers.
In this short article ,we will discuss and understand on setting up Virtual Host in Apache web server in Ubuntu (which is the preferred Operating System among many developers) for web hosting .
After learning and understanding this article ,you will also understand how shared hosting platforms like cpanel or Plesk supports multiple websites behind the hood.
Apache Server:
If you are new to web development , you might wonder what actually is apache server, Let's first understand this:
Apache is an open source and a common, and widely used http web server which is responsible for managing low level web traffic.
Although the most fundamental function of a web server is to handling the request from client and pass it to the application server if necessary and returning the response back to the client based on the request.
Following are the main functions of Apache servers, or in general web servers:
1. Accepting, Handling Request and Returning the Response
Apache receives client requests, serves static content (i.e. html, images or any files )directly to clients, and forwards dynamic requests to application servers (e.g., PHP, Python) for processing before returning responses to clients.
2. Maintains security by Access control , Authorization and Encryption :
Likewise it supports HTTPS communication, which enhances the security of the data.
3. Optimization of Page speed by caching or compression:
Apache can optionally compress content or implement caching strategy before sending it to clients to reduce server load, bandwidth usage and improve page speed .
4. Logging and Monitoring:
Apache logs request details like client IP addresses, URLs, response codes, and timestamps, crucial for troubleshooting, performance monitoring, and security analysis.
5. Load Balancing and Reverse Proxying
In scenarios with heavy traffic, Apache can distribute incoming requests among multiple backend servers to enhance scalability and fault tolerance. Additionally, it can function as a reverse proxy, directing requests to backend servers according to predefined routing guidelines.
Before getting started, you need following prerequisites:
Now, before actually setting up a Virtual Host , you need to get a domain name, where you point the nameserver or ip address of this server to that domain.
You can buy domain from any domain registrars and can buy server hosting from any other web hosting provider. It;s not necessary that you buy both from the same vendor.
If you need to learn how to buy the domain name and attach the nameserver to the domain, let me know in the comments below so, I shall make a blog based on your desired domain hosting provider.
We assume that until this point you have pointed the domain to the current server that you are willing to set up as a virtual host to .
Now let's begin:
$ sudo apt update
$ sudo apt install apache2
This will install apache2 in your ubuntu machine. You can verify this using command
$ apache2 -v
Server version: Apache/2.4.52 (Ubuntu)
Server built: 2024-04-10T17:45:18
You will probably get the response something like this, if your apache server was installed appropriately.
Also you can go to your browser and open http://localhost then it will probably open up a page , if you see the content as image below then your apache server is installed properly.
The standard or default localtion for apache2 to place the virtual host content is /var/www folder. You can use this or you are even free to use any other folders . so , let's assume if your domain is example.com then you create a folder inside /var/www using command:
$ sudo mkdir -p /var/www/example.com/public_html
If you want multiple virtual hosts to setup then you can go on adding similarly like,
$ sudo mkdir -p /var/www/example2.com/public_html
Here, The folder name of domain i.e. (example.com ) stores the application code and script for you website to work , while public_html folder stores the files that are required for users to serve like static files , images, resources and so on. If you website is a static one, you can place all of your code inside public_html.
Since the directory was created by root user, the folder and its subdirectories are owned by root user, so if you want your current user (other than root) wants to make modification to the files and folders then you can run this command.
$ sudo chown -R $USER:$USER /var/www/example.com
Here, $USER is the current logged in user. If you run the command ,each user in this server are allowed to change the folder and files .
Now , you need to add only the permission to current user for this folder , so no unwanted user can access your folder.
sudo chmod -R 755 /var/www
Now, the main work is to create virtual host file for each of the domain you want to point to. This file is basically used as a configuration file for web server i.e. (apache in this case ) to map domain names to specific directories on the server. This is the main file that helps to map a single server to host multiple websites. The configuraiton from this file is taken by apache or any webserver and it uses it to decide where the incoming request are to be forwarded ,keeping each domains logically separated.
When installing the apache server , a default configuration(000-default.conf) is available in the folder /etc/apache2/sites-available/ . To create a new virtual host as per your domain you can create a new file or copy this default file (000-default.conf) and reuse it to create a new configuration.
i.e. copy the 000-default.conf file to the same file name as that of your domain. e.g. if your domain is example.com , create a file named example.com.conf and so on.
Note: The virtual host file name must be same as that of your domain name and conf is the extension of file. E.g. example.com.conf
$ cp sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
Now, edit the conf using command line editor as :
$ sudo nano /etc/apache2/sites-available/example.com.conf
The nano command is used to open up a command line editor to update the following code in the conf file.
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName example.com
DocumentRoot /var/www/example.com
ServerAlias www.example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Save the file and close it.
What this configuration file basically does is: Whenever the request for example.com comes to the apache server, it forwards the request to folder /var/www/example.com,
Similarly, if there are other domain like example2.com then apache checks for the configuration file with name example2.com.conf and looks for the documentRoot line which consists of folder location, this apache then forwards the request to that specific folder specified in example2.com.conf
Here ,
ServerName: refers to the primary domain associated with the virtual host. It tells Apache which domain the virtual host should respond to when a client makes a request.
e.g. example.com
ServerAlias : This directive specifies additional domain names (aliases) that the virtual host should respond to. It allows the virtual host to handle requests for multiple domain names, redirecting them to the same website or serving different content based on the requested domain. E.g. if example.com is server than www.example.com is the server alias
Now, Create a static file named index.html inside folder /var/www/example.com/public_html using same nano command or however you want:
$ sudo nano /var/www/example.com/public_html/index.html
This will open up a text editor in the same command line where you can paste this code
<html>
<head>
<title>This is a Configuration Test page.</title>
</head>
<body>
<h1>The Virtaul host for domain example.com has been configured .</h1>
</body>
</html>
Save and close this file.
You can enable the virtual host configuration using command
$ sudo a2ensite example.com
This will create a symlink from sites-available to sites-enabled folder inside /etc/apache2/ folder , which will enable and apache server starts serving this domain. All the virtual host file that are configured need to be enabled for the apache server to serve those domains.
Every time you make configuration changes, you need to restart the apache server in order for the configuration to apply. Which can be done using Command:
$ sudo service apache2 restart
Now ,go to your browser of your choice and access example.com or your domain name , if all of the above steps are done correctly and you can access your content , then congratulations you have setup your domain , you can add multiple such domains replicating above steps.
If you are able to access your domain and content then you can stop beyond this point, but if you have not yet pointed the domain to your server or the domain propagation has not completed as it might require anytime between 24-48 hours, you can follow the document beyond this , such that you can check the configuration of apache updating host file in local system.
Note: The domain propagation time is suggested to be between 24 hours to 48 hours or may be before that
Hosts file is situated in location /etc/hosts , this file will intercept the request coming to apache and forward to the given host as defined in virtual host of apache configuration file.
So to perform this in ubuntu, open up this file and add a line,
$ sudo nano /etc/hosts
You will see something like this in this file :
127.0.0.1 localhost
127.0.1.1 guest-desktop
192.168.20.200 example.com
On the left side of space add ip of your machine where you are placing your code and domain on your right side of the space as shown above. Save and close this file.
This will direct any requests for your domain on your computer and send them to your server at the designated IP address.
So now if you go to point example.com in your browser you will successfully see the content added earlier, If you see the content of the html page added earlier ,
Congratulations!! You have successfully set up a virtual host in ubuntu. If not please debug and repeat the following steps and verify them., you might have missed something.