How to Configure Apache Virtual Hosts on CentOS7?

To host multiple domains on your server, you need to create corresponding virtual hosts on the web server, allowing it to deliver distinct content for various requests. This guide walks you through creating Apache virtual hosts on CentOS 7.

How to do it

  1. Step 1: Create a Directory Structure

    Establish a directory structure for organizing your website files by creating directories. For example:

    sudo mkdir -p /var/www/mywebsite.com/public_html
  2. Step 2: Assign Permissions

    Allocate permissions accordingly for the directories:

    sudo chown -R apache:apache /var/www/mywebsite.com
    sudo chmod -R 755 /var/www
  3. Step 3: Create an HTML File

    Generate a basic HTML file for testing the virtual host:

    sudo nano /var/www/mywebsite.com/public_html/index.html

    Add the following content:

    <html>
      <head>
        <title>Welcome to mywebsite.com</title>
      </head>
      <body>
        <h1>Hello World!</h1>
      </body>
    </html>

    Save and exit the text editor.

  4. Step 4: Create a Virtual Host Configuration File

    Craft a fresh virtual host configuration file in the /etc/httpd/conf.d/ directory using a text editor such as nano or vim:

    sudo nano /etc/httpd/conf.d/mywebsite.com.conf

    Add the following configuration:

    <VirtualHost *:80>
      ServerAdmin webmaster@mywebsite.com
      ServerName mywebsite.com
      DocumentRoot /var/www/mywebsite.com/public_html
    
      ErrorLog /var/log/httpd/mywebsite.com_error.log
      CustomLog /var/log/httpd/mywebsite.com_access.log combined
    </VirtualHost>

    Save and exit the text editor.

  5. Step 5: Enable the Virtual Host

    Activate the virtual host configuration and restart Apache:

    sudo systemctl restart httpd
  6. Step 6: Update Hosts File (Optional)

    If you're conducting tests on your local machine, consider including an entry in your hosts file:

    sudo nano /etc/hosts

    Add a line like:

    127.0.0.1 mywebsite.com

    Save and exit.

  7. Step 7: Test the Virtual Host

    Open your web browser and navigate to http://mywebsite.com. You should see the "Hello World!" message.

Congratulations! You've successfully configured an Apache virtual host on CentOS 7. Tailor the settings to align with your specific requirements.


Was this article helpful?

mood_bad Dislike 0
mood Like 1
visibility Views: 20577