If you want to host more than one domain on your server, you need to create corresponding hosts on the web server so the server could know what content should be served for the incoming request. In this tutorial, you will learn how to create Apache virtual hosts on CentOS 7.
What you’ll need
Before you begin this guide you’ll need the following:
- SSH root access to the VPS
Step 1 – Installing Apache
First of all, you need to install Apache on your CentoOS 7 machine (skip this step if you already have it installed). Apache can be easily installed from default CentOS repositories with the following command:
sudo yum -y install httpd
Once installation is complete, enable Apache as a CentOS service:
sudo systemctl enable httpd.service
Now Apache will start automatically after server restart.
Step 2 — Creating directory tree
Now you need to create directory tree which will be used to hold website data. Set the working directory to
/var/www by running this command:
You should use unique document root for each created virtual host. In this tutorial yourdomain.com will be used as domain sample, please replace it with your own domain. Run this command to create a directory for the new host:
mkdir -p yourdomain.com/public_html
chown to change directory ownership and
chmod to set correct permissions for the whole web directory so it can be accessed by Apache properly:
chown -R apache:apache /var/www/yourdomain.com/public_html
chmod -R 755 /var/www
Apache now has the required access to serve the content for incoming queries and create additional directories.
Step 3 — Creating demo page
You should create index.html file in
Input this content to the file:
<html> <head> <title>This is a test page</title> </head> <body> <h1>It works!</h1> </body> </html>
Save the file once you are finished.
Step 4 — Creating the Virtual Host
Create a new virtual host .conf file in the Apache configuration directory:
Structure of yourdomain.com.conf file should be like:
<VirtualHost *:80> ServerName www.yourdomain.com ServerAlias yourdomain.com DocumentRoot /var/www/yourdomain.com/public_html ErrorLog /var/www/yourdomain.com/error.log CustomLog /var/www/yourdomain.com/requests.log combined </VirtualHost>
Basically, we tell Apache that we will use 80 port for the communication and that yourdomain.com is the name of this virtual host. Additionally, we specify directories for the website files (document root) and error logs.
In order for these changes to take effect, restart the Apache by executing this command:
systemctl restart httpd.service
That is it, you have just created a virtual host for your domain, try accessing it in your browser. You should see “It works!” page.
Now you have the knowledge how to create Apache virtual hosts on CentOS 7 machine. Now every host could serve different content. Furthermore, you are familiar with the configuration of the virtual host file.