How to let PHP to create subdomain automatically for each user? How to let PHP to create subdomain automatically for each user? php php

How to let PHP to create subdomain automatically for each user?


You're looking to create a custom A record.

I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:

*.mywebsite.com       IN  A       127.0.0.1

127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.


Doing it like http://mywebsite.com/user would be a lot easier to set up if it's an option.

Then you could just add a .htaccess file that looks like this:

Options +FollowSymLinksRewriteEngine OnRewriteRule ^([aA-zZ])$  dostuff.php?username=$1

In the above, usernames are limited to the characters a-z


The rewrite rule for grabbing the subdomain would look like this:

RewriteCond %{HTTP_HOST} ^(^.*)\.mywebsite.comRewriteRule (.*)  dostuff.php?username=%1

However, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like

$username = strtok($_SERVER['HTTP_HOST'], ".");


The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:

<VirtualHost 111.22.33.55>    DocumentRoot /www/subdomain    ServerName www.domain.tld    ServerAlias *.domain.tld</VirtualHost>

However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.


I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.