I just threw together a quick Python script which generates a virtual host file, enables it, creates the web directory and restarts the webserver.
It’s basic – but I found it useful. Maybe someone else will too.
#!/usr/bin/python
import os, sys, getopt
def main(argv):
try:
opts, args = getopt.getopt(argv, "hd:a:", ["help", "domain="])
except getopt.GetoptError:
usage()
sys.exit(2)
if len(opts) < 1:
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--domain"):
domain = a
else:
assert False, "unhandled option"
directory = domain.split('.')[0]
if not os.path.isdir("/var/www/%s" % directory):
os.mkdir("/var/www/%s" % directory)
if not os.path.isdir("/var/www/%s/htdocs" % directory):
os.mkdir("/var/www/%s/htdocs" % directory)
vhost_template = """
ServerName www.__DOMAIN__
ServerAlias __DOMAIN__
DocumentRoot /var/www/__DIR__/htdocs
CustomLog /var/log/apache2/__DOMAIN__-access.log combined
ErrorLog /var/log/apache2/__DOMAIN__-error.log
ErrorDocument 404 /404.html
ErrorDocument 401 /401.html
ErrorDocument 500 /500.html
RewriteEngine On
RewriteCond %{HTTP_HOST} ^__DOMAIN__
RewriteRule (.*)$ http://www.__DOMAIN__$1 [R=301,L]
Options +Indexes FollowSymlinks IncludesNoExec +Includes -MultiViews
AllowOverride All
Order Allow,Deny
Allow from all
"""
vhost = vhost_template.replace('__DIR__', directory).replace('__DOMAIN__', domain)
open('/etc/apache2/sites-available/%s.conf' % directory, 'w').write(vhost)
os.system('a2ensite %s.conf' % directory)
os.system('/etc/init.d/apache2 restart')
def usage():
print 'usage: newv.py [-d domain.com]'
if __name__=="__main__":
main(sys.argv[1:])