Apache Web server

How to Setup Apache Virtual Hosts in CentOS 7

In this tutorial, we will explain how to create Apache virtual hosts on CentOS7.

If you are looking to host more domains on your server, then you need to create corresponding hosts on your web server. In this way, your server can deliver different content for different requests.

Follow the following steps to setup Apache Virtual Hosts in CentOS7

1. How to Install Apache

1. Before we start, make sure that you have root access to your VPS or server using an SSH connection.

To Install Apache on your CentOS7, follow the command:

sudo yum -y install httpd

2. Once it is installed, you need to enable Apache as a CentOS service:

sudo systemctl enable httpd.service

3. Now, visit your server’s IP address and check whether Apache is running or not. Your page should look like this:

2. Now, you need to create a directory tree.

1. Here, a directory tree is used to hold website data and you need to set the working directory to /var/www by running this command:

cd /var/www/

2. You need to use a unique document root for each virtual host:

mkdir -p yourdomain.com/public_html

Note: To replace yourdomain.com with your actual domain name.

3. Try to make the directory accessible to Apache. Now run chown to change the ownership and chmod to set the correct permissions for the whole web directory.

Apache now has the necessary rights to add new directories and serve content in response to incoming queries.

3. Create a Demo Page

It is suggested to create a demo page for each of your Apache virtual hosts. By doing so, you can test the host’s functionality before actually moving your website’s data. Here’s how to do it:

1. Now, use the nano editor to create an index.html file in yourdomain.com/public_html directory:

nano yourdomain.com/public_html/index.html

2. Copy the following content to the file:

    <title>This is a test page</title>
    <h1>It works!</h1>

3. Save the file by pressing CTRL + X and then Y.

4. Create the Virtual Host

1. Create a new virtual host .conf file in the Apache configuration directory:

nano /etc/httpd/conf.d/yourdomain.com.conf

2. Now, insert the following content into the .conf file:

<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

In this above example, we are telling Apache that we will be using port 80 for the communication and that yourdomain.com is the name of the virtual host. Also, we specify directories for the website files (document root) and error logs.

3. Restart Apache

systemctl restart httpd.service

That is it, in this way, you can create an Apache virtual host for your domain!

Leave a Reply

Your email address will not be published. Required fields are marked *