How Do I Create Dynamic Sub-domains With A URL String Variable?

A1WEBSITEPRO QuestionsCategory: QuestionsHow Do I Create Dynamic Sub-domains With A URL String Variable?
Jaqulin asked 7 years ago

Can you give me the steps to creating dynamic sub-domains? Here is the situation. A user comes to my site and signs up for an account. They then enter their information and a sub domain is created for them automatically on my server. I have seen other websites do this. Can you tell me how? Do I have to use htaccess?

How Do I Create Dynamic Sub-domains With A URL String Variable? was last modified: June 19th, 2017 by Jaqulin
1 Answers
Best Answer
Maximus Mccullough Staff answered 7 years ago

HI Jaqulin,
You do not have to use htaccess for this process. However there are 3 steps you must do.

  1. Set Wildcard at your DNS.
  2. Set a server alias in your virtual hosts
  3. Set PHP to grab variables to display the correct information.

OK so here we go. Log into your DNS and add an (A) record to your domain. Point it to your ip address. Here is an example.

*.example.com.   3600  A  127.0.0.1

Click on “Add record” and put an asterisk in. This means wildcard. So if they create xyz.example.com OR abc.example.com it will resolve to your server. You will want to use your servers IP address in an (A) record.
Next you will need to go to your virtual hosts on your Apache server. You will want to look for the virtual hosts configuration for your website. It will end in .conf. When you get in there you will want to look for “ServerAlias” and right beside it you will want to put *.example.com. Here is an example.

<VirtualHost *:80>
 ServerName server.example.com
 ServerAlias *.example.com
</VirtualHost>

Finally you will want to grab just the sub-domain part to display the correct information. In PHP it will look something like this.

Only cool people share!

[php][<?php
$urlg = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;
$array=parse_url($urlg);
$array[‘host’]=explode(‘.’, $array[‘host’]);
$url=$array[‘host’][0];
?>[/php]

Answer for How Do I Create Dynamic Sub-domains With A URL String Variable? was last modified: June 19th, 2017 by Maximus Mccullough