Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Aastha Shrivastava
Aastha Shrivastava

Posted on

     

Automating Virtual Host setup on your server

Are you also one of those who frequently need to setup VHosts in order to test,create etc new sites and you feel doing the whole process again and again is time consuming and well.. BORING? Then this article is for you!

Note: The script used in this article is written for anyLinux distro withApache server, but you may still get a general idea of how to use it for your requirements.

Here we will create a simple bash script to automate the whole vhost setup process which includes:

  • Creating a new folder for your website.
  • Creating configuration files for the website.
  • Configuring thehosts file and
  • Enabling the vhost.

Creating template files

Before we start working on our script we will need these template files which we use in the setup:

  • A templateconf file to create configuration for the vhost.
  • A templateindex.html file for default homepage of our newly created vhost

This is how my template files looks like:
default-index.html

<html><head><title>Home|New Virtual Host</title></head><body><h1>Welcome!</h1>         You just created a new virtual host!<br>        Go ahead and add some files in your brand new vhost</body></html>
Enter fullscreen modeExit fullscreen mode

default-vhost.conf

<VirtualHost *:80>        ServerName 127.0.0.x        ServerAlias example.local        ServerAdmin admin@example.local        DocumentRoot /var/www/example.local        ErrorLog ${APACHE_LOG_DIR}/error.log        CustomLog ${APACHE_LOG_DIR}/access.log combined</VirtualHost>
Enter fullscreen modeExit fullscreen mode

You can create similar files based on your requirements.

Now let's get started with the script.

Gettingsitename andhost from command line

Let's start by getting the input parameters as command line arguments. We will use the flags:

  • -s: for sitename
  • -h: for host

We will also use a flag-d (optional) in case user wants to create a new project directory for the vhost.

We will usegetopts to get the arguments, if you are not familiar withgetopts you can check outthis article.

This is how we can take input from command line:

whilegetoptss:h:d flagdocase"${flag}"ins)sitename=${OPTARG};;                h)host=${OPTARG};;                d)createdir=1;;echo"Added entry in hosts file"*)echo"Invalid option: -$flag";;esacdone
Enter fullscreen modeExit fullscreen mode

We are storing the values we got from input insitename andhost variable and settingcreatedir to 1.

Creating and configuring project directory

Next we will create a folder in/var/www and copy ourdefault-index.html file in that folder:

if[[$createdir-eq 1]]thenmkdir /var/www/$sitenamecpdefault-index.html /var/www/$sitename/index.html
Enter fullscreen modeExit fullscreen mode

We are checking if user has specified the-d flag or not, you can remove the condition if you always want create a new directory for your vhost. You can also skip this step depending on your requirement.

Now that we have created the directory let's change the owner to current logged-in user:

chown$SUDO_USER:$SUDO_USER /var/www/$sitename
Enter fullscreen modeExit fullscreen mode

This is because only the super user has permissions to create files and folders invar/www, so we are changing the owner of the folder so that the current user will have full control over the folder.

This script needs to be run using sudo,$SUDO_USER contains user name of user which is executing the script usingsudo.

Now let's change the permission for

chmod755 /var/www/$sitenamefi
Enter fullscreen modeExit fullscreen mode

Creating configuration files

Now we will create theconf file for our site in/etc/apache2/sites-available/ using or default template:

cd /etc/apache2/sites-available/cpdefault-vhost.conf$sitename.confsed-i"s/example.local/$sitename/g"$sitename.confsed-i"s/127.0.0.x/$host/g"$sitename.conf
Enter fullscreen modeExit fullscreen mode

Heresed orstream editor is a command line tool for editing, we are usingsed to replaceexample.local with$sitename and127.0.0.x with$host in our conf file.

Configuring hosts file

Currently your/etc/host must look like something like this :

127.0.0.1       localhost...# The following lines are desirable for IPv6 capable hosts::1     ip6-localhost ip6-loopbackfe00::0 ip6-localnet...
Enter fullscreen modeExit fullscreen mode

We want to add the host and sitename before# The following lines are desirable... line. For this we will once again use thesed:

sed-i"0,/# The following lines are desirable for IPv6 capable hosts/s/^# The following lines are desirable.*/$host$sitename\n&/" /etc/hosts
Enter fullscreen modeExit fullscreen mode

Enabling virtual host and restarting the server

Now let's enable our vhost usinga2ensite command and reload apache:

a2ensite$sitename.confsystemctl reload apache2echo"All done! Visit your newly created virtual host at https://example123.local"
Enter fullscreen modeExit fullscreen mode

And that's it! Phew! We just created a simple script to automate vhost configuration. Let's go ahead and execute it:

sudo ./create-conf.sh -s example123.local -h 127.0.0.12 -dAll done! Visit your newly created virtual host at https://example123.local
Enter fullscreen modeExit fullscreen mode

Let's visit our newly created virtual host
Alt Text

Here is how our full script looks like:

#!/bin/bash
whilegetoptss:h:d flag
do
case
"${flag}"in
s)sitename=${OPTARG}
;;
h)host=${OPTARG}
;;
d)createdir=1
;;
*)echo"Invalid option: -$flag";;
esac
done
# Create and configure folder in/var/www if option if option selected
if[[$createdir-eq 1]]
then
mkdir /var/www/$sitename
echo"Folder /var/www/$sitename created"
# Creating dummy landing page
cpdefault-index.html /var/www/$sitename/index.html
echo"Intitialized with index page"

# Changing owner and permission of the folder
chown$SUDO_USER:$SUDO_USER /var/www/$sitename
chmod755 /var/www/$sitename
echo"Modified permissions and owner"
fi
# Creating configuration files
cd /etc/apache2/sites-available/
cpdefault-vhost.conf$sitename.conf
sed-i"s/example.local/$sitename/g"$sitename.conf
sed-i"s/127.0.0.x/$host/g"$sitename.conf
echo"Configuration files created"

# Configuring hosts file
sed-i"0,/# The following lines are desirable for IPv6 capable hosts/s/^# The following lines are desirable.*/$host$sitename\n&/" /etc/hosts
echo"Added entry in hosts file"

# Enabling virtual host and restarting the server
a2ensite$sitename.conf
systemctl reload apache2
echo"Restarted apache"
echo"All done! Visit your newly created virtual host at https://$sitename"

Enter fullscreen modeExit fullscreen mode




Final Thoughts

Though this script may not fully work with your requirement you can definitely get an idea of how to make one for yourself do let me know in the comments what you think about it!

References:

Setting up Virtual Host on Ubuntu 20
Taking command line arguments using flags in bash
Stream Editor to insert line
How to use sed to find and replace text in files in Linux / Unix shell

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
fenix profile image
Fenix
Building in Public | FLOSS ~ Copyleft heart ~@~ a.k.a. 'Don Hugo ;-) '
  • Location
    Fediverse | Cyberspace
  • Joined

Thanks for sharing !

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Pune, India
  • Joined

More fromAastha Shrivastava

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp