Web Server Intermediate

Apache Virtual Host Creator

Automatically creates, configures and activates new virtual host for Apache.

Published: April 05, 2024

Detailed Information

This script creates, configures, and activates a new virtual host for Apache web server. Used to host multiple websites on the same server.

What Does This Script Do?

This script automates Apache virtual host setup:

  • Creates document root directory
  • Sets directory permissions
  • Creates virtual host configuration file
  • Creates test index.html file
  • Enables site
  • Reloads Apache

Why Should You Use It?

Virtual host creation simplifies web server management:

  • Quick Setup: Automation instead of manual configuration
  • Standard Configuration: Best practice settings
  • Time Savings: Setup with single command

How to Use

Step-by-Step Usage Guide

1. Run Script

sudo chmod +x create_vhost.sh
sudo ./create_vhost.sh

2. Answer Questions

The script will ask you:

  • Domain name (e.g., example.com)
  • Document root (default: /var/www/example.com)

3. DNS Configuration

Point your domain to server IP.

Requirements

Requirements

  • Apache: Apache web server must be installed
  • Root Privileges: Script must be run as root

Use Cases

Use Cases

1. New Website Setup

Create virtual host for a new website.

2. Multi-Site Management

Host multiple websites on the same server.

Examples

Usage Examples

Example 1: Basic Usage

sudo ./create_vhost.sh
# Domain: example.com
# Document root: (Enter - default used)

Code

#!/bin/bash

# Apache Virtual Host Creator

if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root"
    exit 1
fi

read -p "Enter domain name: " DOMAIN
read -p "Enter document root (default: /var/www/$DOMAIN): " DOCROOT
DOCROOT=${DOCROOT:-/var/www/$DOMAIN}

mkdir -p "$DOCROOT"
chown -R www-data:www-data "$DOCROOT"

cat > "/etc/apache2/sites-available/${DOMAIN}.conf" << EOF
<VirtualHost *:80>
    ServerName $DOMAIN
    ServerAlias www.$DOMAIN
    DocumentRoot $DOCROOT
    
    <Directory $DOCROOT>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog \${APACHE_LOG_DIR}/${DOMAIN}-error.log
    CustomLog \${APACHE_LOG_DIR}/${DOMAIN}-access.log combined
</VirtualHost>
EOF

# Create index file
cat > "$DOCROOT/index.html" << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to $DOMAIN</title>
</head>
<body>
    <h1>$DOMAIN is working!</h1>
</body>
</html>
EOF

a2ensite "${DOMAIN}.conf"
systemctl reload apache2

echo "✓ Virtual host created successfully!"
echo "Document root: $DOCROOT"
echo ""
echo "Add to /etc/hosts for local testing:"
echo "127.0.0.1 $DOMAIN"

Usage

sudo chmod +x create_vhost.sh
sudo ./create_vhost.sh

# Enter domain name
# Specify document root (optional)

Troubleshooting

Troubleshooting

Problem: "a2ensite: command not found"

Solution: Install Apache:

sudo apt-get install apache2

Tags

apache virtual host vhost web server