Configuring Apache Virtual Hosts on Linux

By Chandrashekhar Fakirpure

Updated on May 10, 2024

In this tutorial, we explain set up and configuring Apache Virtual hosts on Linux. We have covered Debian-based and Red Hat-based systems. Virtual hosts allow you to host multiple websites on a single server by directing traffic based on the domain name requested by the client.

Prerequisites

Before you begin, ensure that you have the following:

  • A Linux server with Apache installed.
  • Basic knowledge of the Linux command line.
  • A root user access or normal user with administrative privileges (Use sudo)

Step 1: Installing Apache (If Not Already Installed)

If Apache is not already installed on your Linux server, you can install it using the package manager. On Debian-based systems (such as Ubuntu), you can use apt, and on Red Hat-based systems (such as CentOS), you can use yum.

For Debian-based systems:

apt update
apt install apache2

For Red Hat-based systems:

dnf install httpd

After installation, start the Apache service:

systemctl start apache2   # Debian-based
systemctl start httpd     # Red Hat-based

Step 2: Creating Virtual Host Configuration Files

Apache virtual host configurations are stored in individual files within the /etc/apache2/sites-available/ directory on Debian-based systems and /etc/httpd/conf.d/ directory on Red Hat-based systems.

Create a new configuration file for each virtual host you want to set up. For example:

nano /etc/apache2/sites-available/example.com.conf   # Debian-based
vi /etc/httpd/conf.d/example.com.conf              # Red Hat-based

Add the following configuration to the file, replacing example.com with your domain name and /var/www/example.com/public_html with the path to your website files:

<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

Step 3: Enabling Virtual Hosts

After creating the virtual host configuration files, you need to enable them by creating symbolic links in the appropriate directory.

On Debian-based systems:

a2ensite example.com.conf

On Red Hat-based systems:

sudo ln -s /etc/httpd/conf.d/example.com.conf /etc/httpd/conf-enabled/

Step 4: Restart Apache

To apply the changes, restart the Apache service:

systemctl restart apache2   # Debian-based
systemctl restart httpd     # Red Hat-based

Step 5: Testing

Finally, test your configuration by visiting your domain in a web browser. If everything is set up correctly, you should see your website.

Conclusion

Congratulations! You have successfully configured Apache virtual hosts on Linux server, allowing you to host multiple websites on a single server. You can repeat the steps above to add more virtual hosts as needed.