php – dynamic subdomain system


I recently saw an app/site called Sarahah, and an interesting feature was that when registering, the username became a subdomain, something like "", is there any way to do this mod rewrite or some apache configuration without actually creating other subdomains?


web server

People don't notice, but this is already set up by default on your web server.

When you access a domain that has been pointed to your server, but your server doesn't have any virtual host configured to receive that domain, it delivers the contents of the web server's default directory. In most cases in /var/www/html .

All you have to do is configure your application inside the web server's default directory and program it there to deliver specific content based on the domain accessed. Be it done in PHP, NodeJS, Python or whatever. All of them have resources to read the requested domain.

In PHP, for example, you can find out which domain was used to reach your application through the global variable $_SERVER['HTTP_HOST'] .

But, there is a catch there. DNS entries still need to account for the subdomain.

DNS entries

For this to actually work without having to keep creating DNS entries in your domain for each user, you have to configure your domain to respond with a wildcard .

Instead of creating a DNS entry per user, you create a single entry that will answer for anything. See below.

The normal would be (which we are used to doing):

(A|CNAME) -> -> serverIP
(A|CNAME) -> -> serverIP
(A|CNAME) -> -> serverIP
(A|CNAME) -> -> serverIP

An entry using wildcard would be:

(A|CNAME) -> * -> serverIP

With a wildcard entry configured and your application placed in your web server's default directory, all you have to do now is the above: identify the domain being accessed through your application.

Not everything is flowers

Most DNS managers (the tool you use to keep track of your domain) do not support or allow the use of wildcards . CloudFlare is an example of those that don't.

But then all you have to do to resolve this issue is find a DNS manager that allows you to and point your domain to it. For registration purposes, DigitalOcean's DNS manager allows the use of wildcards .

Scroll to Top