How to let PHP to create subdomain automatically for each user?
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} !-f
RewriteRule ^(.*)$ /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.example/album/Dance/now
I get back
http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example
Then in my index.php
code I just explode my username off of the hostName. This gives me nice pretty SEO URLs.
We setup wildcard DNS like they explained above. So the a record is *.yourname.example
Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.
We use the following code:
$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);
This code just sets the $account
variable the same as the subdomain. You could then retrieve their files and other information based on their account.
This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess
this method should work (as long as your host will setup the wildcard for you).
We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.
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.example
ServerAlias *.domain.example
</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
.
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.example 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.
Then you need to configure your web-server to serve all subdomains.
- Nginx:
server_name .mywebsite.example
- Apache:
ServerAlias *.mywebsite.example
Regarding .htaccess, 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'], ".");
If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user
would be a lot easier to set up if it's an option.