Apache Virtual Hosts

Related video:

Setting up Apache virtual hosts can become quite tedious if it is frequently repeated.

Wouldn't it be nice if we could automate the process?

Here is where scripting comes to the rescue!

You can use the following Bash script to make your life a little easier.

It will create the folder structure for every site in the "domains" array (under the "/var/www/html/" folder), create the necessary Apache config files, modify the "/etc/hosts" file, and restart Apache. The only thing you will have to do, is to navigate to "http://siteName.local/". Isn't that enough?

vhost-create() {
    if [[ -n "$1" ]]; then
        if [[ ! -d "${base_path}/${domain}" ]]; then
            sudo mkdir "${base_path}/${domain}";
            sudo mkdir "${base_path}/${domain}/public_html/";
            sudo mkdir "${base_path}/${domain}/logs/";
            echo "${domain}.local has been created successfully." | sudo tee "${base_path}/${domain}/public_html/index.html";
            echo "

    # Enable the site with sudo a2ensite site_name && sudo systemctl restart apache2

    # SSLEngine On
    # SSLCertificateFile  /etc/ssl/certs/ssl-cert-snakeoil.pem
    # SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

    ServerName ${domain}.local
    ServerAlias www.${domain}.local
    ServerAdmin ${domain}@localhost
    DocumentRoot /var/www/html/${domain}/public_html
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
    LogLevel info warn
    ErrorLog /var/www/html/${domain}/logs/error.log
    CustomLog /var/www/html/${domain}/logs/access.log combined
" | sudo tee "/etc/apache2/sites-available/${domain}.local.conf";
            sudo a2ensite "${domain}.local";
            echo "   ${domain}.local" | sudo tee --append /etc/hosts;
            sudo systemctl restart apache2;
            echo "Done.";
            echo "You can access the site at http://${domain}.local/";
            echo "${domain} already exists. Skipping...";
        echo "Usage: vhost-create ";