Search code examples
.htaccesssubdomainwildcard-subdomain

Fake subdomain for different users while still browsing same folder structure


I'd like to create fake subdomains for different users for more vanity, and to make the user (in this case a company) feel they are in a more isolated environment.

For the sake of maintainability, it's important for me that all users still browse the same files, to avoid having to update files for every single user that exists when updating the code.

My website has one public part at root, let's say www.example.com. I'd like to be able to fake the following kind of subdomains:

user1.example.com

The true URL would be www.example.com/member/?user=user1. I'd like for the folder structure to follow the same pattern. www.example.com/member/settings/?user=user1 would appear as user1.example.com/settings/ and so on.

I assume this would best be achieved with .htaccess, no?. What is the proper .htaccess code for this?

Thank you!


Solution

  • In the end, this was super easy to solve! It wasn't solved the way I first expected though, using .htaccess. I solved it with something called wildcard subdomain.

    When you register a new subdomain, enter * in the domain prefix, such as *.example.com. A folder for the wildcard subdomain will be created on your server, such as _wildcard_.example.com. Whenever you access site1.example.com, fakesub.example.com etc, the browser of the visitor will read the files in the wildcard.example.com folder.

    The beauty of it all is that if I create a certain subdomain that I want to use, for example forum.example.com, this real subdomain will have priority over the wildcard subdomain, and files will be fetched from the folder for this subdomain, as opposed to from the wildcard subdomain folder.

    I use PHP and need to know the subdomain to fetch the appropriate database for the current user. To do this, I use the following code:

    $subdomain = explode('.', $_SERVER['HTTP_HOST'])[0]
    

    With a wildcard SSL cert I have all of these subdomains secure.