The cart is empty

Setting up virtual hosts on the Apache web server in CentOS 7 is a crucial task for managing multiple domains or subdomains on a single physical server. This allows Apache to host various websites efficiently, making it an ideal choice for hosting providers and developers who need to manage different web pages effectively. This article will guide you through the basic process of setting up virtual hosts on Apache in CentOS 7.

Prerequisites

Before we begin, ensure that you have Apache web server installed on your CentOS 7. You can do this by using the command yum install httpd -y in the terminal. Also, make sure that your firewall allows HTTP and HTTPS traffic.

Step 1: Creating Directory Structure

For each virtual host, you should create a separate directory containing all the files of that website. This approach simplifies management and security. For example:

sudo mkdir -p /var/www/example.com/public_html

Step 2: Assigning Permissions

It's important to set the correct permissions for the directories and files of your websites. This ensures that Apache can properly read and write data while maintaining system security.

sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chmod -R 755 /var/www

Step 3: Creating a Demo Page for Testing

For testing purposes, it's useful to have a simple HTML page in each virtual host directory. This allows you to verify that Apache correctly routes requests.

echo "<html><body><h1>Success: example.com is working!</h1></body></html>" | sudo tee /var/www/example.com/public_html/index.html

Step 4: Configuring a New Virtual Host

Apache in CentOS 7 uses configuration files for each virtual host located in /etc/httpd/conf.d/. To create a new virtual host, create a new configuration file:

sudo vi /etc/httpd/conf.d/example.com.conf

In this file, define the configuration for your virtual host. Here's a basic example:

<VirtualHost *:80>
    ServerAdmin This email address is being protected from spambots. You need JavaScript enabled to view it.
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog /var/www/example.com/error.log
    CustomLog /var/www/example.com/requests.log combined
</VirtualHost>

Step 5: Restart Apache and Testing

After creating and saving the configuration file, restart Apache to apply the changes:

sudo systemctl restart httpd

 

Finally, test the configuration by opening a web browser and entering your virtual host's domain. If everything is set up correctly, you should see your test HTML page.

 

Setting up virtual hosts on Apache in CentOS 7 is a relatively straightforward process that allows you to efficiently manage multiple websites from a single server. It's important to adhere to best practices in security and management to ensure smooth and secure operation of your websites.