Apache Virtual Host Creation using Bash Script in Ubuntu
https://www.zyxware.com/sites/default/files/styles/user_image/public/default_images/index.png?itok=2YmREnrP
BY sudheesh.s
1 year ago
Virtual-host
1
comments comment

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


RELATED ARTICLE

more_horiz
close

on 20th August 2015 / by chithra.k
What do you usually go to create a virtual host? If I am right, then you will copy the default file, change the contents, add entry in host file and then you will enable the site, right? Well, if you are thorough with the above steps, then I would advise you not to waste your time any more by repeating the steps each time you need to create a virtual host, because I am going to provide you a script using which you can easily create a virtual host. Step 1 : Copy the following script and save as .sh file. #!/bin/bash name=$1 WEB_ROOT_DIR=$2 email='webmaster@localhost' sitesEnable='/etc/apache2/sites-enabled/' sitesAvailable='/etc/apache2/sites-available/' userDir='/var/www/' sitesAvailabledomain=$sitesAvailable$name.local echo "Creating a vhost for $sitesAvailabledomain with a webroot $WEB_ROOT_DIR" ### create virtual host rules file echo " <VirtualHost *:80> ServerAdmin $email ServerName $name.local DocumentRoot $WEB_ROOT_DIR <Directory $WEB_ROOT_DIR/> Options Indexes FollowSymLinks AllowOverride all </Directory> </VirtualHost<" > $sitesAvailabledomain echo -e $"\nNew Virtual Host Created\n" sudo sed -i "1s/^/127.0.0.1 $name.local\n/" /etc/hosts sudo a2ensite $name.local sudo service apache2 reload echo "Done, please browse to http://$name.local to check!" Step 2 : Open terminal and navigate to the folder where the script file resides. Grant executable permission to this file(chmod a+x filename.sh). Step 3 : Type sudo ./filename.sh virtual_host_name /directory-path. This will create a virtual host "virtual_host_name.local" which will point to the directory-path.I would advice you not to use this script if you don't know the steps to create a virtual host, because you shouldn't always use shortcuts in your life. Learn the correct way and then use this. Note : The above code works if the apache version is less than 2.4. If your Apache version is 2.4, then add the following code inside the script file. #!/bin/bash ### First parameter is the domain name and second parameter is the web-root. name=$1 WEB_ROOT_DIR=$2 email='webmaster@localhost' sitesAvailable='/etc/apache2/sites-available/' sitesAvailabledomain=$sitesAvailable$name.local.conf echo "Creating a vhost for $name.local with a webroot $WEB_ROOT_DIR" ### create virtual host rules file. echo " <VirtualHost *:80> ServerAdmin $email ServerName $name.local DocumentRoot $WEB_ROOT_DIR <Directory $WEB_ROOT_DIR/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory> </VirtualHostlt;" > $sitesAvailabledomain echo -e $"\nNew Virtual Host Created\n" ### Add the domain name to hosts file. sudo sed -i "1s/^/127.0.0.1 $name.local\n/" /etc/hosts ### Enable the site and reload the apache. sudo a2ensite $name.local.conf sudo service apache2 reload echo "Done, please browse to http://$name.local to check!" Hope this helps, happy coding. Do you need any web hosting support or need any services, connect with us. Virtual host Leave a reply Your email address will not be published. Required fields are marker *
more_horiz
close

on 24th August 2015 / by akhila.vn
Virtual host setup in Ubuntu is very simple, we can do this in few steps. The following commands will help you to download the latest version of all software from its repositories(that is updation) and then install 'apache2', if you have no apache2 software. Otherwise ignore the following commands and go through the main steps for VirtualHost setup. sudo apt-get update sudo apt-get install apache2 Main steps for VirtualHost setup. Open your terminal, take a copy of the default .conf file from /etc/apache2/sites-available/ and open it in gedit editor (if you have no gedit application, just use your own editor for modifying the entries in the file. sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/myproject.conf sudo gedit /etc/apache2/sites-available/myproject.conf Remove all the default content in myproject.conf, add the following code in it and save it.<VirtualHost *:80> ServerName myproject.local ServerAdmin webmaster@localhost DocumentRoot /home/user/public_html/myproject_folder <Directory /home/user/public_html/myproject_folder> Require all granted AllowOverride All </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Enable your currently added virtual host file.sudo a2ensite myproject.conf Then restart your Apache using the following command.sudo service apache2 restart Its not finish, now set up localhost file by editing the 'hosts' file from 'etc'. For this, first you have to open 'hosts' file in gedit using the following command :sudo gedit /etc/hostsNow, you have to enter, 127.0.0.1 myproject.local Ok, lets open your browser and type URL as 'myproject.local' for getting your site. It will work. Checkout other virtual host related articles now. For any other services get in touch with us. Virtual host Ubuntu Leave a reply Your email address will not be published. Required fields are marker *
close

on 07th December 2017 / by sudheesh.s
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 Download the virtualhost bash script zip folder Download Unzip the virtualhost.zip file Go to virtual host folder Right click and select open in terminal (or change directory to the virtualhost folder in terminal) 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 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 Enter your domain name 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 Enter virtual host root folder full path like /var/www/html/testing 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 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. 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 If the user entered ‘n’ for no, then it will ask for their Apache configuration path 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) 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 For default configuration, create root folder in /var/www/html/ folder with user given domain name 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 ]]; thenFor 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" ]]; thenCheck 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 fiElse show the warning message and exit else echo " " echo "You have no virtual host domain root folder" echo "Please try again!" echo " " exit FiFor other directories, just create it else # For other directories, just create it mkdir $1 echo " " echo "$1 has been created" FiGet 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 fiLog 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 serversudo 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 Virtual host BASH Scripting Leave a reply Your email address will not be published. Required fields are marker * anoop (not verified) access_time 22 Feb 2019 - 10:59 Thanks , Its saved my time Add new comment
Leave a reply
Your email address will not be published. Required fields are marker *

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

author-image
anoop (not verified)
access_time 22 Feb 2019 - 10:59

Thanks , Its saved my time