Dynamic subdomain system

Asked

Viewed 1,397 times

12

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?

2 answers

6


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 has none virtual host configured to receive this domain, it delivers the contents of the default web server directory. In most cases /var/www/html.

All you have to do is configure your application within the default web server directory and program it to deliver specific content based on the domain you accessed. Be it done in PHP, Nodejs, Python or whatever. They all have the resources to read the requested domain.

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

But there is a catch there. DNS entries still need to answer by subdomain.

DNS entries

In order for this to actually work without you having to keep creating DNS entries on your domain for each user, you have to set up your domain to respond with a wildcard.

Instead of creating a DNS entry per user, you create a single entry that will account 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 configured wildcard entry and your application placed in the default directory of your web server, all you have to do now is what was said above: identify the domain being accessed through your application.

It’s not all flowers

Most DNS managers (the tool you use to make your domain notes) do not support or allow the use of wildcards. Cloudflare is an example of those who don’t allow it.

But then all you have to do to solve this issue is find a DNS manager that allows you to do that and point your domain to it. For logging purposes, Digitalocean’s DNS manager allows the use of wildcards.

4

Good and simple solution via . htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.yourwebsite.com
RewriteCond %{HTTP_HOST} ([^.]+)\.yourwebsite.com
RewriteRule ^(.*)$ /path_to_your_site/httpdocs/work_out.php?url=$1

source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.