Apache HTTP Server is a popular open-source web server that uses a modular architecture. Virtual hosts allow a single Apache instance to serve multiple websites independently, each with its own configuration and content.

How to Do It

  1. Step 1: Create Directory Structure

    Set up a directory structure for organizing your website files:

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

    Set the appropriate permissions for the directories:

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

    Generate a simple HTML file for testing the virtual host:

    echo "<html><head><title>Welcome to My Website</title></head><body><h1>Hello World!</h1></body></html>" | sudo tee /var/www/mywebsite.com/public_html/index.html
  4. Step 4: Create Virtual Host Configuration File

    Create a virtual host configuration file in the /etc/apache2/sites-available/ directory using a text editor like nano or vim:

    sudo nano /etc/apache2/sites-available/mywebsite.com.conf

    Add the following configuration:

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

    Save and exit the text editor.

  5. Step 5: Enable the Virtual Host

    Enable the virtual host configuration and restart Apache:

    sudo a2ensite mywebsite.com.conf
    sudo systemctl restart apache2
  6. Step 6: Update Hosts File (Optional)

    If you are testing on your local machine, add an entry to your hosts file:

    sudo nano /etc/hosts

    Add the following line:

    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, confirming that your virtual host is configured correctly.