#!/bin/bash
# Step 1: Prompt for domain name
read -p "Enter the domain name: " domain_name
read -p "Enter the proxy server IP: " proxy_ip
read -p "Enter the proxy server port: " proxy_port
# Step 2: Create the initial virtual host file
echo "<VirtualHost *:80>
ServerName $domain_name
ServerAlias www.$domain_name
</VirtualHost>" > /etc/apache2/sites-available/$domain_name.conf
# Step 3: Enable the site with a2ensite
sudo a2ensite $domain_name.conf
# Step 4: Obtain SSL certificates using Certbot
sudo certbot --apache -d $domain_name
# Step 5: Reload Apache to apply changes
sudo systemctl reload apache2
# Step 6: Disable the old sites before deleting them
sudo a2dissite $domain_name.conf
sudo a2dissite $domain_name-le-ssl.conf
# Step 7: Delete temporary configuration files
sudo rm /etc/apache2/sites-available/$domain_name.conf
sudo rm /etc/apache2/sites-available/$domain_name-le-ssl.conf
# Step 8: Create the final virtual host file with SSL and proxy settings
echo "<VirtualHost *:80>
ServerName $domain_name
ServerAlias www.$domain_name
# Redirect all HTTP to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Certbot renewal challenge
Alias /.well-known/acme-challenge /var/www/letsencrypt/.well-known/acme-challenge
<Directory /var/www/letsencrypt/.well-known/acme-challenge>
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:443>
ServerName $domain_name
ServerAlias www.$domain_name
# SSL Configuration (managed by Certbot)
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/$domain_name/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/$domain_name/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
# Security Headers
Header always set Strict-Transport-Security \"max-age=63072000; includeSubDomains; preload\"
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
# Proxy Configuration
ProxyPreserveHost On
ProxyPass / http://$proxy_ip:$proxy_port/
ProxyPassReverse / http://$proxy_ip:$proxy_port/
# Forward original client information
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1 ::1 $proxy_ip
# Set protocol headers
RequestHeader set X-Forwarded-Host \"$domain_name\"
RequestHeader set X-Forwarded-Proto \"https\"
RequestHeader set X-Forwarded-Port \"443\"
RequestHeader set X-Requested-With \"XMLHttpRequest\"
RequestHeader set X-Forwarded-Scheme \"https\"
# Enable HTTP/2
Protocols h2 http/1.1
# Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>
</VirtualHost>" > /etc/apache2/sites-available/$domain_name-ssl.conf
# Step 9: Enable the SSL site
sudo a2ensite $domain_name-ssl.conf
# Step 10: Reload Apache to apply the final changes
sudo systemctl reload apache2
echo "VirtualHost for $domain_name has been set up with SSL and proxy configuration."