Package: vhost-gen
vhost-genContinuous Integrationvhost-genwill dynamically generatevhostorreverse proxy(with or withoutwebsocket support) configuration files for Apache 2.2, Apache 2.4 and Nginx depending on what you have set inconf.yml. This makes it easy to switch between different web servers while keeping the exact same functionality.InstallationVia pippipinstallvhost-genFrom gitNote:When using the Makefile, ensure thatpyyamlis installed (pip install pyyaml).gitclonehttps://github.com/devilbox/vhost-gencdvhost-gen
sudomakeinstallWhat is all the fuzz?Imagine you have to create virtual hosts for your web server over and over again. The only things that might change are document root, log files and server names and possibly some other minor changes. Instead of having to copy and adjust the server's vhost config file each time, you can usevhost-gento generate them for you. By supporting different web server versions, it makes it also easy for you to switch back and forth between Apache 2.2, Apache 2.4 and Nginx.# vHost$vhost-gen-p/shared/httpd/www.example.com-nwww.example.com# Reverse Proxy$vhost-gen-rhttp://127.0.0.1:8080-l/-napi.example.comvhost-genalone simply creates a new virtual host every time you execute it. The goal however is to also automate the execution of the vhost generator itself.1. Reverse Proxy automation:watcherpHere enterswatcherpthe game.watcherplistens for changes of port bindings and triggers a command whenever a new port has been bound or a binding has been removed. By combining these two tools, you could automate the creating of reverse proxies with one command:# %n will be replaced by watcherp with the address a port has binded# %p will be replaced by watcherp with the the actual port number that started binding# -p argument from watcherp specifies ports to ignore for changes$watcherp-v\-p80,443\-a"vhost-gen -r 'http://%n:%p' -l '/' -n '%n.example.com' -s"\-d"rm /etc/nginx/conf.d/%n.example.com.conf"\-t"nginx -s reload"2. Virtual Host automation:watcherdHere enterswatcherdthe game.watcherdlistens for directory changes and triggers a command whenever a directory has been created or deleted. By combining these two tools, you could automate mass virtual hosting with one command:# %n will be replaced by watcherd with the new directory name# %p will be replaced by watcherd with the new directory path$watcherd-v\-p/shared/httpd\-a"vhost-gen -p %p -n %n -s"\-d"rm /etc/nginx/conf.d/%n.conf"\-t"nginx -s reload"More customizationNow it might look much more interesting. With the above command every vhost will have the exact same definition (except server name, document root and log file names). It is however also possible that every vhost could be customized depending on their needs.vhost-genallows for additional overwriting its template. So inside each newly created folder you could have a sub-directory (e.g.templates/) with folder specific defines. Those custom templates would only be sourced if they exist:# Note: Adding -o %p/templates$watcherd-v\-p/shared/httpd\-a"vhost-gen -p %p -n %n -o %p/templates -s"\-d"rm /etc/nginx/conf.d/%n.conf"\-t"nginx -s reload"Making it robustIf you don't trust the stability ofwatcherdor want other means of controlling this daemon, you can utilizesupervisord:[program:watcherd]command=watcherd -v -p /shared/httpd -a "vhost-gen -p %%p -n %%n -s" -d "rm /etc/nginx/custom.d/%%n.conf" -t "nginx -s reload"startsecs=0autorestart=truestdout_logfile=/dev/stdoutstdout_logfile_maxbytes=0stderr_logfile=/dev/stderrstderr_logfile_maxbytes=0stdout_events_enabled=truestderr_events_enabled=true3. DockerizingIf you don't want to implement it yourself, there are already four fully functional dockerized containers available that offer automated mass virtual hosting based onvhost-genandwatcherd:Base ImageWeb serverRepositoryNginx stable (official)nginxhttps://github.com/devilbox/docker-nginx-stableNginx mainline (official)nginxhttps://github.com/devilbox/docker-nginx-mainlineApache 2.2 (official)Apache 2.2https://github.com/devilbox/docker-apache-2.2Apache 2.4 (official)Apache 2.4https://github.com/devilbox/docker-apache-2.4InsightsSupported WebserverIf you are not satisfied with the default definitions for the webserver configuration files, feel free to open an issue or a pull request.NameTemplate with default definitionsNginxnginx.ymlApache 2.2apache22.ymlApache 2.4apache24.ymlSupported FeaturesDocument serving vHost or Reverse Proxy (with or w/o websocket support)Custom server nameCustom document rootCustom access log nameCustom error log nameEnable cross domain requests with regex support for originsEnable PHP-FPMAdd Aliases with regex supportAdd Deny locations with regex supportEnable webserver status pageAdd custom directives from the configuration fileHow does it work?General information:vHost name is specified as a command line argumentvHost templates for major webservers are defined in etc/templatesvHost templates contain variables that must be replacedWebserver type/version is defined in /etc/vhost-gen/conf.ymlVariable replacer are defined in /etc/vhost-gen/conf.ymlAdditional variable replacer can also be defined (-o)The following describes the program flow:vhost-genwill read /etc/vhost-gen/conf.yml to get defines and webserver type/versionBase on the webserver version/type, it will read etc/templates/<HTTPD_VERSION>.yml templateVariables in the chosen template are replacedThe vHost name (-n) is also placed into the templateTemplate is written to webserver's config location (defined in /etc/vhost-gen/conf.yml)UsageUsing different configurationsTheconfiguration fileshould give you a lot of flexibility to generate a customized virtual host that fits your needs. Go and check out theexamplesection to see different configuration files for different web servers. If however the customization available in the configuration file is not sufficient, you can also adjust thetemplatesitself. Read on to find out more in the next section.Adding custom directivesTheconfiguration filealso contains acustom:directive. This is to add customized directives into your vhost definition that are not yet included in the feature sections. An example for Nginx would be:conf.yml:custom: |
  if (-f $request_filename) {
      break;
  }This would then be added to your generated vhost:server{...if(-f$request_filename){break;}}If the current vHost definition does not suit your needs, you could also disable all available features in the configuration file and only use thecustom:directive to specify your required definitions.Using different templatesEachtemplateconsists of two sections:vhostfeaturesThevhostsection is the actual vhost that is being built. All placeholders (In the form of:__*__) will be substituted from either the configuration file or the feature section of the template.Thefeaturessection contains definitions of features that can be enabled or disabled (via the config file). If those features do not seem suitable, you can adjust them to better fit your needs. You can also re-arrange their position in thevhostsection.Whenever you edit the template, make sure not to misspell any placeholders. They will not get replaced when spellt wrong.Let's take for example thefeatures.server_statussection from Apache 2.2:server_status: |
    # Status Page
    <Location __REGEX__>
        SetHandler server-status
        Order allow,deny
        Allow from all
    </Location>If you are not satisfied with theAllow from allpermissions, simply rewrite this template to your needs:server_status: |
    # Status Page
    <Location __REGEX__>
        SetHandler server-status
        Order allow,deny
        Allow from 160.120.25.65
    </Location>Available command line optionsUsage:vhost-gen-p|r<str>-n<str>[-l<str>-c<str>-t<str>-o<str>-d-s-v]vhost-gen--helpvhost-gen--version

vhost-genwilldynamicallygeneratevhostconfigurationfilesforNginx,Apache2.2orApache2.4dependingonwhatyouhavesetin/etc/vhost-gen/conf.yml

Requiredarguments:-p|r<str>Youneedtochooseoneofthemutuallyexclusivearguments.-p:Pathtodocumentroot.-r:http(s)://Host:Portforreverseproxy.-r:ws(s)://Host:Portforreverseproxywithwebsocketsupport.Depeningonthechoice,itwilleithergenerateadocumentservingvhostorareverseproxyvhost.Note,whenusing-p,thiscanalsohaveasuffixdirectorytobesetinconf.yml-l<str>Locationpathwhenusingreverseproxy.Note,thisisnotrequiredfornormaldocumentrootserver(-p)-n<str>NameofvhostNote,thiscanalsohaveaprefixand/orsuffixtobesetinconf.yml

Optionalarguments:-m<str>Vhostgenerationmode.Possiblevaluesare:-mplain:Onlygeneratehttpversion(default)-mssl:Onlygeneratehttpsversion-mboth:Generatehttpandhttpsversion-mredir:Generatehttpsversionandmakehttpredirecttohttps-c<str>Pathtoglobalconfigurationfile.Ifnotset,thedefaultlocationis/etc/vhost-gen/conf.ymlIfnoconfigisfound,adefaultisusedwithallfeaturesturnedoff.-t<str>Pathtoglobalvhosttemplatedirectory.Ifnotset,thedefaultlocationis/etc/vhost-gen/templates/Ifvhosttemplatefilesarenotfoundinthisdirectory,theprogramwillabort.-o<str>Pathtolocaloverridevhosttemplatedirectory.Thisisusedasasecondarytemplatedirectoryanddefinitionsfoundherewillbemergedwiththeonesfoundintheglobaltemplatedirectory.Note,definitionsinlocalvhostteplatedirectorytakeprecedenceovertheonesfoundintheglobaltemplatedirectory.-dMakethisvhostthedefaultvirtualhost.Note,thiswillalsochangetheserver_namedirectiveofnginxto'_'aswellasdiscardinganyprefixorsuffixspecifiedforthename.Apachedoesnothaveanyspecialities,thefirstvhosttakesprecedence.-sIfspecified,thegeneratedvhostwillbesavedinthelocationfoundinconf.yml.Ifnotspecified,vhostwillbeprintedtostdout.-vBeverbose.Usetwicefordebugoutput.

Miscarguments:--helpShowthishelp.--versionShowversion.ContributingThis is an open source project and done in spare time. If you want to help out you are warmly welcome. You could do one or more of the following things:Validate web server templatesSubmit template examplesCreate templates for other web serversWhatever else you can imagine ofLicenseMIT LicenseCopyright (c) 2017cytopia