Add a sub domain and create a separate virtual host through code

Posted November 24, 2020 718 views
PHPUbuntu 20.04DigitalOcean Droplets

Hi! I have a CRM that is already published. Now I want to sell it on subscription basis. I want to clone the same application as soon as a new client registers and pay the fee. For that I need a sub domain automatically through code and the virtual host too. Not through the CPanel. I will just copy the current application and the database it is using for every new client and he/she will access it through a sub domain which will be named after their username. Help will be appreciated greatly. Thanks!

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
1 answer

Hi there @deevannaveed,

If you have a cPanel server, then what you could do is use the cPanel/WHM API to create new accounts for your new users. It will look like this:

  • whmapi1 createacct username=username bwlimit=unlimited cgi=1 cpmod=paper_lantern customip= dkim=1 featurelist=feature_list forcedns=0 frontpage=0 gid=123456789 hasshell=0 hasuseregns=1 homedir=/home/user ip=n language=en owner=root mailbox_format=mdbox max_defer_fail_percentage=unlimited max_email_per_hour=unlimited max_emailacct_quota=1024 maxaddon=unlimited maxftp=unlimited maxlst=unlimited maxpark=unlimited maxpop=unlimited maxsql=unlimited maxsub=unlimited mxcheck=auto password=123456luggage pkgname=my_new_package plan=default quota=1024 reseller=0 savepkg=1 spamassassin=1 spf=1 spambox=y uid=123456789 useregns=1

You can take a look at the documentation here:

If you don’t have cPanel what you could do is to have a template of a and then update the details in there. For example, your Vhost template could look like this:

<VirtualHost *:80>

        ServerName DOMAIN_NAME
        ServerAlias www.DOMAIN_NAME

        DocumentRoot /var/www/DOMAIN_NAME/public

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

        <Directory /var/www/DOMAIN_NAME/public>
                Options Indexes FollowSymLinks
                AllowOverride All
                Require all granted
        Protocols h2 http/1.1

Then you could just substitute the DOMAIN_NAME part with the domain name of the specific user. If you are planning to do it with a shell script you could use the sed command:

sed -i "s/DOMAIN_NAME/${domain}/g" ${domain}.conf

Then you can copy that Vhost into the sites-available folder:

  • cp ${domain}.conf /etc/apache2/sites-available/${domain}.conf

Then to enable the Vhost you could do something like this:

# Enable the new Vhost
a2ensite ${domain}
# Run a Config test
apache2ctl -t
# Restart Apache if config test is OK
if [[ $? -eq 0 ]] ; then
    echo "Config test was ok, restarting Apache.."
    systemctl restart apache2

Hope that this helps!