php – dynamic subdomain system

Question:

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

Answer:

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) -> usuario1.dominio.com.br -> serverIP
(A|CNAME) -> usuario2.dominio.com.br -> serverIP
(A|CNAME) -> usuario3.dominio.com.br -> serverIP
(A|CNAME) -> usuario4.dominio.com.br -> serverIP

An entry using wildcard would be:

(A|CNAME) -> *.dominio.com.br -> 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