Search code examples
phpsubdomain

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


How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?

To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?


Solution

  • 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.