The Apache web server is the most popular way of serving web content on the internet. It accounts for more than half of all active websites on the internet and is extremely powerful and flexible. 

Apache Virtual Hosts allows you to run more than one website on a single machine. With Virtual Hosts, you can specify the site document root (the directory which contains the website files), create a separate security policy for each site, use different SSL certificates and much more.

In this tutorial we will show you how to set up Apache Virtual Host on a CentOS 8 server.

Installing Apache

Apache is available in the default CentOS repositories.

# dnf install httpd

Enable and start the Apache service.

# systemctl enable httpd
# systemctl start httpd

Open your web browser and go to your server. http://server-ip/ you will see something like this.

Create the directory structure for each host

We will create a separate directory for each domain we want to host on our server inside the /var/www directory.

# mkdir -p /var/www/example.com/

Apache should be made the owner of that folder.

# chown -R apache: /var/www/example.com

Creating Virtual Host

By default, Apache is configured to load all configuration files that ends with .conf from the /etc/httpd/conf.d/ directory.

# nano /etc/httpd/conf.d/example.com.conf

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com

DocumentRoot /var/www/example.com
ErrorLog /var/log/httpd/example.com-error.log
CustomLog /var/log/httpd/example.com-access.log combined

</VirtualHost>

To test the Apache configuration, run the following command.

# httpd -t
Syntax OK

Restart Apache service.

# systemctl restart httpd

Test your Results

To test your virtual host, you’ll have to create a phpinfo file to the document root directory.

# echo "<?php phpinfo();" > /var/www/example.com/index.php

Now we can test our webserver. Go to your browser and access your server hostname. You should see your server’s PHP information.

This means virtual host can run properly with Apache web server. You have successfully set it up.

Tagged: