Have you ever been curious when you register to a website, how a subdomain is created with your username? For example, you register as “myname” in example.com and a subdomain myname.example.com is created on the fly. Initially it seems very complex process to create dynamic subdomains, but when you understand process then it’s fairly easy. In this post we will dive into creating a dynamic subdomains for your site.

Requisite

Before proceeding you need to have following access with you.

  1. DNS access/modification rights
  2. Web server’s root access/ssh

Adding DNS Record

Go to your DNS management console and add “A” Name record with following details:

*.example.com       IN  A       127.0.0.1

 

 

Here, 127.0.0.1 is web server’s public IP.

Updating .conf file of Apache2

SSH into your web server and update the apache2 config file reflecting your details.

<VirtualHost *:80>
       DocumentRoot /abs/path/to/webroot
       ServerName   example.com
       ServerAlias *.example.com
       <Directory /abs/path/to/webroot>
               AllowOverride All
               Order allow,deny
               Allow from all
       </Directory>
</VirtualHost>

 

 

Now restart your apache2 server using following command:

sudo service apache2 restart

Testing the dynamic subdomains

Now open your browser and enter http://myuser.example.com , this should open the root of your host. You can try as many subdomain as you want. Now you want to access the subdomain in your code, so that you can bifurcate the user. Below PHP code will give you the subdomain part.

$subdomain = explode('.', $_SERVER['HTTP_HOST']) ;

$user = $subdomain[0];

 

 

$user is the variable which hold the subdomain part. You can use it to identify the user.

That’s it. By following these simple steps you can have dynamic subdomains. Please ask any question if you may have in comment section below.

 

Want to work with us? We're hiring!