Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Enable all Apache Config Files


Apache, BASH, Sysadmin
David Egan

Use this BASH script to quickly enable all Apache virtual host configurations.

THis can be handy if for example you are setting up a new development environment.

Background: Enabling Virtual Hosts in Apache 2.4

To set up Apache 2.4 virtual host configurations under Debian/Ubuntu you add a configuration file with a <VirtualHost> block in the /etc/apache2/sites-available directory.

Such config files must have the .conf file extension.

To enable the site, you need to run the a2ensite script, passing the config filename as an argument. This creates a symlink to the config file in the /etc/apache2/sites-enabled directory. You then need to reload Apache.

Script

The following script loops through all config files in /etc/apache2/sites-available and runs a2ensite. There’s no problem if any site is already enabled, since this does not result in an error.

#!/bin/bash
#
# Enable all config files in /etc/apache2/sites-available directory.
#
# Usage: Make this script executable and run as a user with sudo privileges.
# ==============================================================================

BASE_DIR="/etc/apache2/sites-available"

for FILEPATH in $BASE_DIR/*; do
  if [[ -f "$FILEPATH" ]]; then
    CONF=$(basename "$FILEPATH")
    a2ensite ${CONF}
    if [ $? != 0 ]
    then
      echo "a2ensite NOT successful for ${CONF}"
    else
      echo "a2ensite successful for ${CONF}"
    fi
  fi
done

# Reload apache
read -p "Do you want to reload Apache (y/n)?" CONT
if [ "$CONT" = "y" ]; then
    service apache2 reload
    if [ $? -eq 0 ]
    then
      echo "Apache reloaded - check sites in browser."
    else
      echo "There was a problem reloading Apache."
    fi
else
  echo "Changes won't take effect until Apache is reloaded or restarted.";
fi

TL;DR

Copy across the contents of /etc/apache2/sites-available from the old environment to the new (e.g. with rsync).

Download and run the above script:

# Make a directory if necessary
mkdir -p ~/sysadmin/apache
cd ~/sysadmin/apache

# Get the script
curl https://gist.githubusercontent.com/DavidCWebs/509e6e8829e24fb7cfa1e6c82c2b24e2/raw/982693b8de7082acb44082274628de0a63593929/a2enmod-all.sh -o a2enmod-all.sh

# Make executable
sudo chmod +x a2enmod-all.sh

# Run script
sudo ./a2enmod-all.sh

Move across /etc/hosts from the old environment to the new.

References


comments powered by Disqus