Skip to content

Instantly share code, notes, and snippets.

@amcchord
Created October 4, 2024 16:13
Show Gist options
  • Save amcchord/405f9e7125aedfdb70d0df400fd1fdcf to your computer and use it in GitHub Desktop.
Save amcchord/405f9e7125aedfdb70d0df400fd1fdcf to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if script is run as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
# Check if domain name is provided
if [ -z "$1" ]; then
echo "Please provide a domain name as an argument."
echo "Usage: $0 example.com [subdomain]"
exit 1
fi
DOMAIN=$1
SUBDOMAIN=${2:-"www"}
FULL_SUBDOMAIN="$SUBDOMAIN.$DOMAIN"
SUBDOMAIN_ROOT="/var/www/$FULL_SUBDOMAIN"
SUBDOMAIN_CONF_FILE="/etc/apache2/sites-available/$FULL_SUBDOMAIN.conf"
# Create subdomain web root directory if it doesn't exist
if [ ! -d "$SUBDOMAIN_ROOT" ]; then
mkdir -p "$SUBDOMAIN_ROOT"
chown -R www-data:www-data "$SUBDOMAIN_ROOT"
chmod -R 755 "$SUBDOMAIN_ROOT"
echo "<h1>Welcome to $FULL_SUBDOMAIN</h1>" > "$SUBDOMAIN_ROOT/index.html"
fi
# Create Apache virtual host configuration for subdomain if it doesn't exist
if [ ! -f "$SUBDOMAIN_CONF_FILE" ]; then
cat << EOF > "$SUBDOMAIN_CONF_FILE"
<VirtualHost *:80>
ServerName $FULL_SUBDOMAIN
DocumentRoot $SUBDOMAIN_ROOT
ErrorLog \${APACHE_LOG_DIR}/$FULL_SUBDOMAIN-error.log
CustomLog \${APACHE_LOG_DIR}/$FULL_SUBDOMAIN-access.log combined
</VirtualHost>
EOF
# Enable the subdomain site
a2ensite "$FULL_SUBDOMAIN.conf"
# Reload Apache to apply changes
systemctl reload apache2
fi
# Check if certbot is installed, if not, install it
if ! command -v certbot &> /dev/null; then
apt update
apt install -y certbot python3-certbot-apache
fi
# Set up Let's Encrypt certificate for subdomain
certbot --apache -d "$FULL_SUBDOMAIN" --non-interactive --agree-tos --email webmaster@"$DOMAIN" --redirect
# If setting up www subdomain, also set up the bare domain
if [ "$SUBDOMAIN" == "www" ]; then
# Create Apache virtual host configuration for bare domain if it doesn't exist
BARE_DOMAIN_CONF_FILE="/etc/apache2/sites-available/$DOMAIN.conf"
if [ ! -f "$BARE_DOMAIN_CONF_FILE" ]; then
cat << EOF > "$BARE_DOMAIN_CONF_FILE"
<VirtualHost *:80>
ServerName $DOMAIN
DocumentRoot $SUBDOMAIN_ROOT
ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined
</VirtualHost>
EOF
# Enable the bare domain site
a2ensite "$DOMAIN.conf"
# Reload Apache to apply changes
systemctl reload apache2
fi
# Set up Let's Encrypt certificate for bare domain
certbot --apache -d "$DOMAIN" --non-interactive --agree-tos --email webmaster@"$DOMAIN" --redirect
fi
echo "Setup completed for $FULL_SUBDOMAIN"
if [ "$SUBDOMAIN" == "www" ]; then
echo "Setup also completed for $DOMAIN"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment