Skip to content

Instantly share code, notes, and snippets.

@iamajeesh
Last active October 24, 2023 01:47
Show Gist options
  • Save iamajeesh/3ae688b706f235e40bdf3dad595ed4a6 to your computer and use it in GitHub Desktop.
Save iamajeesh/3ae688b706f235e40bdf3dad595ed4a6 to your computer and use it in GitHub Desktop.
create a quick virtual host bash script
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <domain>"
exit 1
fi
domain="$1"
# Check if the virtual host file already exists
config_file="/etc/apache2/sites-available/${domain}.conf"
if [ -e "$config_file" ]; then
echo "Virtual host for $domain already exists."
exit 1
fi
# Create a new virtual host configuration file
cat > "$config_file" <<EOF
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName $domain
ServerAlias www.$domain
DocumentRoot /var/www/html/$domain
<Directory /var/www/html/$domain>
Options 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 the website directory if it doesn't exist
web_dir="/var/www/html/$domain"
if [ ! -d "$web_dir" ]; then
mkdir -p "$web_dir"
fi
# Enable the virtual host and reload Apache
a2ensite "$domain.conf"
systemctl reload apache2
echo "Virtual host for $domain has been added."
# how to use
# chmod +x add_virtual_host.sh
# ./add_virtual_host.sh mydomain.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment