How to Setup dynamic sub domain for your website

Do you ever noticed that how github and slack accomplished this. github uses the subdomain under github.io domain for static hosted wiki pages. for example if your github username is example then your subdomain will be example.github.io and your content will be there like a static website. Similar approach has been followed by slack team. You has different subdomain for each workspace in slack.

We know that domains are static I mean, we have to manually declare A record in our domain’s DNS console while specifying sub domain. So how we setup these dynamic sub domains. let’s have a look.

For this you need to customize your domain’s dns and your web server. In my case DNS is Godaddy and web server is nginx. You can do the same with any other DNS provider and web server.

Customize your Domain DNS

For this login in to your dns control panel and find the location where you can add A records . Now Since we want to setup our subdomain to be dynamic, we will be using wild card character “*” rather than any specific name. This will accept all sub-domain incoming request and map to the mentioned IP address. See the screenshot below.

Customize your Nginx Server

You have pointed your sub-domain to ip running nginx server. So it’s time to configure nginx to point the domain to required folder or proxy script (node or php-fpm app). We will do the same here as we have done with dns. Include the wild card character ‘*’ in server_name property of server block.

server {
    root /var/www/your_app_folder;
    index index.php index.html index.htm;
    server_name *.example.com;

    location / {
        try_files $uri =404;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    }
}

Now the every sub-domain is pointed to your app. You can write your app logic to further recognize the sub-domain and process accordingly. For an instance, for php app you can get the request’s sub-domain with the following snippet.

list($ext, $domain, $subDomain) = array_reverse(explode('.', $_SERVER['HTTP_HOST']));
if (!empty($subDomain)) {
    echo "Your accessing site on <b>" . $subDomain . "</b> sub-domain";
} else  {
    echo "Your accessing site on <b>" . $domain . "</b> main domain";
}

I hope you enjoyed the article. Leave your comments below. Thanks for your time.

Comments

Write a Reply or Comment

Your email address will not be published.