Add VirtualServer automatically to Apache

May 16, 2014 1.2k views
Hi, Currently, I add a VirtualServer to Apache manually for each site I want to host. Is there any way to add it programmatically? Means create a VirtualServer, Create a directory in /var/www/ and copy some files into it. Is there any API to do so? I'm running VirtualMin/Webmin but that is also a manual process. Anything to automate all this?
2 Answers
There isn't any API, but it is certainly something you could script. Something like this would handle the basic use case:


if [ ! -n "$1" ]; then
echo "No host set."

echo "Creating new VirtualHost /var/www/$1/"

touch /etc/apache2/sites-available/$1

mkdir /var/www/$1

cat << EOF > /etc/apache2/sites-available/$1
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName $1

DocumentRoot /var/www/$1/
<Directory />
Options FollowSymLinks
AllowOverride None
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined

a2ensite $1
service apache2 reload
@Andrew, thank you for the code.
Have another answer? Share your knowledge.