Apache Virtual Host Creation using Bash Script in Ubuntu

| | 7 min read

Setting up a new virtual host in Apache usually requires a number of steps such as creating and enabling the virtual host configuration file in /etc/apache2/sites-available/ path, setting up local hosts file and so on.

This bash script will perform all those steps for you. Thus you don’t need to manually do those steps anymore. You just need to download the virtual host bash script, change its permission to "Executable" and execute it.

Steps for downloading the virtualhost bash script, changing its permission and executing the script are explained below.

STEPS

  1. Download the virtualhost bash script zip folder Download
  2. Unzip the virtualhost.zip file
  3. Go to virtual host folder
  4. Right click and select open in terminal (or change directory to the virtualhost folder in terminal)
  5. Verify the executable permission of the virtualhost file and if it doesn’t have executable permission, apply permission to execute using the command
    sudo chmod 755 virtualhost
  6. Run the script using the command -
    sudo ./virtualhost

Virtual host bash script explanation

  • The virtual host bash script asks for the user to enter the domain name.
  • The user can give the custom virtual host root folder full path.
  • By default the virtual host root folder will be
    /var/www/user_given_domainname .
  • If the user given virtual host root folder doesn't exist, it will create it for the user, with the user's approval.
  • The user can give the Apache configuration path, if the user had configured it in a different path other than the default path(/etc/apache2/sites-available).
  • A custom doc folder will be created in parallel with the virtual host root folder in their parent directory for the error and access logs of the custom virtual host.
  • If a folder of the same name already exists, then the log files will be placed in there.

Example

Run the script using sudo ./virtualhost

image7.png

Enter your domain name

image9.png

After entering the domain name it will ask for the virtual host root folder full path. Note that you should give the full path of the virtual host root folder

image6.png

Enter virtual host root folder full path like /var/www/html/testing

image2.png

If the entered root folder doesn’t already exist, then the program will ask your permission to create it and proceed with the virtual host creation

image5.png

If the user pressed the key ‘y’ for yes, then the script will create the virtual host root folder otherwise it will display an error message saying that there is no custom virtual host root folder and the program will be terminated.

image8.png

Now the program will ask the user whether they want to use the default Apache configuration path (/etc/apache2/sites-available/) for configuring the virtual host configuration file or not. If the answer is ‘y’ then it will proceed with the default configuration path, otherwise, it will ask the user to enter their Apache configuration path

image10.png

If the user entered ‘n’ for no, then it will ask for their Apache configuration path

image4.png

After entering the Apache configuration path, the program will proceed with the configuration of the virtual host and finally if everything went smoothly, then it will show the success message which gives you the details of the virtual host link, virtual host root folder & virtual host error & access log folder (doc folder)

image1.png
image3.png

Code explanation

Getting the domain name from user

read -p "Domain name? " domain_name

If the user wants to point the virtual host using the default configuration, they can execute the script using the command

sudo ./virtualhost -y

This is checked in the following code snippet and the default paths are defined

if [[ $1 = "-y" ]]; then
 echo "You are using default configuration now"
 domain_path="/var/www/html/$domain_name"
 x='y'
 make_directory $domain_path $x
 apache_path="/etc/apache2/sites-available"

If the user doesn’t want to use the default configuration, then get the virtual host root folder path and Apache configuration folder path(optional) from the user.

To make this process easier create 2 functions check_directory() and make_directory()

Define function check_directory() to verify whether the user given directory exists or not

check_directory () {
   if [ ! -d $1 ]; then
       echo "The given directory doesn't exist!"
       echo "Please try again"
       exit
   fi
}

Define function make_directory() to make a directory if it doesn’t exist already

# Function to create a directory
make_directory() {

Check whether the directory already exists or not

if [ ! -d $1 ]; then

For virtual host domain root folder, there will be 2 cases

  1. For default configuration, create root folder in /var/www/html/ folder with user given domain name
  2. Ask the user, whether they want us to create it for them and if the answer is yes then create it for the user
   # For virtual host domain root folder
       if [[ $1 = $domain_path ]]; then

For default configuration, second argument of the function call will be the flag value “y”

 if [[ $2 = "y" ]]; then
           echo " "
           x="y"

Otherwise ask the user, whether they want us to create it for them and if the answer is yes then create it for the user

   else
           echo "$1 directory doesn't exist"
           echo "Do you want to create this virtual host root folder?"

           # Get the user input
           read -p "[Press 'y' for yes and any other key for no] : " x
         Fi

     # Check whether the user input is key 'y'
     if [[ $x = "y" ]]; then

Check whether the virtual host root directory path is created or not. If the mkdir process is unsuccessful, it means that the virtual host root directory path is invalid. So throw an error and exit

  # Check whether mkdir process is successful or not
               if [[ `mkdir -p $1` -ne 0 ]]; then

                   # Apply rwx permission
                   chmod 755 $1
                   echo "$1 has been created for you"
               else    # If mkdir process returned error then it means the virtual host
                   # root folder path is invalid. So throw an error message and exit

                   echo "Error while creating $1"
                   echo "Please check your directory path and try again"
                   echo " "
                   exit
               fi

Else show the warning message and exit

   else
               echo " "
               echo "You have no virtual host domain root folder"
               echo "Please try again!"
               echo " "
               exit
           Fi

For other directories, just create it

  else # For other directories, just create it
           mkdir $1
           echo " "
           echo "$1 has been created"
       Fi

Get the virtual host root folder full path from user. Note that, the path needs to be full path of the virtual host root folder or there will be an error when you run the virtual host in browser.

read -p "Enter root folder full path: " domain_path

Call the make_directory() to create the $domain_path

# Check whether virtual host domain path exists or not
   # If not, create directory
   make_directory $domain_path  

Check whether the user wants to use the default /etc/apache2/sites-available/ path for configuring virtual host configuration file

echo "Do you want to use the default /etc/apache2/sites-available/ path for configuring virtual host configuration file?"
   read -p "[Press 'y' for yes and any other key for no] : " x 

If the user wants to use the default Apache configuration path to setup the virtual host configuration file, set apache_path variable to that path

  if [[ $x = "y" ]]; then
       Apache_path = "/etc/apache2/sites-available" 

If the user wishes to change the default Apache configuration path for configuring virtual host configuration file, get the path from the user.

   else # Get the apache folder path from user
       read -p "Enter your path for configuring virtual host configuration file : " apache_path  

Also check whether the path exists or not

  # Check whether apache path exists or not
       check_directory $apache_path  

Check whether the domain already exists in the virtual host root folder

  if [ -e $apache_path/$domain_name.conf ]; then
   echo "----------------------------"
   echo "This domain already exists!"
   echo "Please try another one"
   echo "----------------------------"
   exit
fi

Log folder(/doc) needs to be in parallel with virtual host root directory. For that purpose go one directory up from the root folder and set $domain_name_log folder there.

(Later we will write the error log file and access log file for this virtual host in that directory)

Remove the last directory from the $domain_path and add /doc folder to it and store it in $domain_log_path folder

  domain_log_path=${domain_path%/*}"/doc"
echo " "
echo "You need to create $domain_log_path folder for log files"

Create $domain_log_path folder

  make_directory $domain_log_path
echo "For error log and access log files"

Add domain name into hosts file

sudo echo "127.0.0.1 $domain_name" >> /etc/hosts

Write the virtual host configuration file and place it in Apache folder path

  sudo echo "
   
       ServerName $domain_name
       ServerAdmin webmaster@localhost
       DocumentRoot $domain_path
       
           Options Indexes FollowSymLinks
           AllowOverride All
           Require all granted
       

Create custom virtual host error log file and access log file in the doc folder

  ErrorLog "$domain_log_path/$domain_name"_error.log
           CustomLog "$domain_log_path/$domain_name"_access.log combined
   " > $apache_path/$domain_name.conf   

Change directory to apache folder path

cd $apache_path

Enable the virtual host configuration file

sudo a2ensite $domain_name.conf

Restart the apache server
sudo service apache2 restart

Print the success message

  echo " "
echo "----------------------------"
echo "You have successfully created the domain : http://$domain_name"
echo "Virtual host root folder : $domain_path"
echo "Error & access logs folder (doc folder) : $domain_log_path"
echo "----------------------------"
exit

NOTE:

If you catch this error -

Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.
while executing the bash script to create your virtual host, it means that something went wrong while creating the apache virtual host and an error has occurred to the apache server.

To fix this error, remove your virtual host configuration file from the apache sites-available/ folder and from sites-enabled/ folder (or run the command a2dissite user_given_domain_name.conf) and restart apache by using the command - sudo service apache2 restart