Add VirtualServer automatically to Apache

Posted May 16, 2014 2.8k 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?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
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.