176

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?

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Skuta
  • 5,830
  • 27
  • 60
  • 68
  • Perhaps its not required to ask your provider for DNS access, since subdomain routing (answer of Mark) already activated! Just try in your browser if subdomains give you a result. And then route them with the .htaccess file. – powtac Oct 08 '08 at 23:15
  • If you can use `wildcard subdomains` this can be achieved in `.htaccess`. See my solution. – Dan Bray Apr 06 '16 at 19:05

12 Answers12

147

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
  • 1
    Unless each subdomain is served off of a different server, I would thing creating Canonical Name (CNAME) records would be a better plan. http://en.wikipedia.org/wiki/List_of_DNS_record_types – theraccoonbear Oct 08 '08 at 17:54
  • The subdomain does look nice. It's going to be a lot more work to set up though because you'll have to make sure that all subdomain requests get handled properly. This isn't terrible with Apache but might be tricky in a hosted environment. – Mark Biek Oct 08 '08 at 17:55
  • @theraccoonbear Assuming you can use wildcards with CNAME as well, that's a thought. – Mark Biek Oct 08 '08 at 17:55
  • Does it actually mean that PHP code would have to add a new Rewriterule to htacccess only? – Skuta Oct 08 '08 at 17:57
  • If you get the DNS and rewrite rules set up properly, you'll just be passing whatever the current username is into PHP as a GET variable. Then you can handle it from there however you want. – Mark Biek Oct 08 '08 at 18:00
  • PHP shouldn't have to worry about adding anything. It just deals with what gets fed to it. – Mark Biek Oct 08 '08 at 18:02
  • Mark, I tried to put that "http://mywebsite.com/user into .htaccess however the website did not display. I guess something went wrong with hosting ^^ Some "IIS Password" problem. – Skuta Oct 09 '08 at 13:10
  • 3
    I should have been more specific. .htaccess is for Apache, not IIS. I'm not sure how url rewriting is handled with IIS but I believe there have been some questions about there on SO. – Mark Biek Oct 09 '08 at 14:02
  • 1
    hi mark, I followed the steps you gave above but the when I do http://xyz.mydomain.com it redirects to http://xyz.mydomain.com/cgi-sys/defaultwebpage.cgi... Do I need to do anything else then steps mentioned above ? – Ashish Rajan Apr 01 '11 at 11:06
  • Hi Mark, I think the problem is due to the IP address as I have a shared hosting... So is there any solution to this situation – Ashish Rajan Apr 01 '11 at 11:32
  • Ashish, I think your best bet is to post a new question on http://serverfault.com/ with the specifics of your configuration. – Mark Biek Apr 01 '11 at 12:22
  • I'm used the above code, its worked for me. But when i put www.domain.com its treating www also a sub domain. Can u revise your code ? – Radhakrishna Rayidi Sep 20 '13 at 17:46
  • @MarkBiek:Do we need to write other things in htaccess file e.g Mod rewrite ON and other things or simply the logic explained above can work? sorry for lack of knowledge here i dont know much about HTACCESS – noobie-php Sep 25 '14 at 13:03
  • @noobie-php, yes you'd need mod_rewrite and AllowOverride set for your webroot (so you can have a .htaccess file). There are lots of good Apache/htaccess tutorials out there explaining that stuff in more detail. – Mark Biek Sep 26 '14 at 12:54
  • Is possible do this in a web app with CodeIgniter? – Tom Oct 31 '15 at 02:28
  • How to add A RECORD on ubuntu Im using LEMP server? Thanks God Bless sir really need your help – Goper Leo Zosa Mar 03 '16 at 09:13
  • @GoperLeoZosa, You'll probably have more luck asking that question on http://unix.stackexchange.com/ – Mark Biek Mar 03 '16 at 16:20
  • See my solution. I have it working perfectly just using `.htaccess` and a `wildcard subdomain`. – Dan Bray Apr 06 '16 at 19:22
  • @MarkBiek Tumblr making the profile urls like this ? If yes please answer my question ? https://stackoverflow.com/questions/54011867/how-to-make-a-tumblr-style-profile-url – AlwaysStudent Jan 03 '19 at 13:54
35

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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
balupton
  • 47,113
  • 32
  • 131
  • 182
22

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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
gradbot
  • 13,732
  • 5
  • 36
  • 69
16

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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • 3
    I think this sould be currect answer , As op ask about how **PHP** handle subdmoins NOT How web or DNS **Servers** handel subdomains . – Salem Apr 24 '16 at 13:09
8

Don't fuss around with .htaccess files when you can use [Apache mass virtual hosting][1].

From the documentation:

#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs

In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.

The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig. [1]: http://httpd.apache.org/docs/2.0/vhosts/mass.html

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Willem
  • 918
  • 5
  • 10
  • 1
    I am not really sure how to use that.. and in the end, why not to mess up with htaccess? – Skuta Oct 09 '08 at 13:06
6

Simple PHP solution for subdomains and multi-domain web apps

Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve example.org

A record => *.example.org
A record => *.example.net

Step 2. Check uniquity of logins when user registering or changing login. Also, avoid dots in those logins.

Step 3. Then check the query <?php

        // Request was http://qwerty.example.org
        $q = explode('.', $_SERVER['HTTP_HOST']);
        /*
            We get following array
            Array
            (
                [0] => qwerty
                [1] => example
                [2] => org
            )
        */

        // Step 4.
        // If second piece of array exists, request was for
        // SUBDOMAIN which is stored in zero-piece $q[0]
        // otherwise it was for DOMAIN

        if(isset($q[2])) {
            // Find stuff in database for login $q[0] or here it is "qwerty"
            // Use $q[1] to check which domain is asked if u serve multiple domains
        }

?>

This solution may serve different domains

qwerty.example.org
qwerty.example.net

johnsmith.somecompany.example
paulsmith.somecompany.example

If you need same nicks on different domains served differently, you may need to store user choise for domain when registering login.

smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Alex Khimich
  • 788
  • 9
  • 10
4

In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.

theraccoonbear
  • 4,283
  • 3
  • 33
  • 41
3

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.

warren
  • 32,620
  • 21
  • 85
  • 124
3

This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.example$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.example$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, create a folder for your subdomain and place the subdomains files.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Dan Bray
  • 7,242
  • 3
  • 52
  • 70
1

I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.

kiwixz
  • 1,380
  • 15
  • 23
1

You can accomplish this via two steps.

  1. Setup wildcard subdomain
  2. Get the subdomain entered by user
  3. Validate the subdomain

1. Setup wildcard subdomain

This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows creating a sub domain in namecheap

  • go to cPanel
  • go to sub domains
  • enter "*" as the value of subdomain

Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.

2. Get the subdomain entered by user

You can now add a php file in the wildcard directory in file manager.

<?php
    
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>

<!DOCTYPE html>
<html lang="en">
    
  <head>
      
    <title>Wildcard Subdomain</title>
    
  </head>
  
  <body>
      <h1>The visitor went to 
      <?php 
        
        echo "<br>";
        
        print("link is: ".$link);
        
        print("<br><br>");
        
        echo "actual file: ".$actual_link;
      ?> 
      </h1>
        
  </body>
</html>

3. Validate the subdomain

You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Hex Heager
  • 107
  • 7
0

Create Dynamic Subdomains using PHP and .htaccess

#(1) Root .htaccess This file is redirection http://www.yourwebsite.example to http://yourwebsite.example for home page use. All of the subdomain redirection to yourwebsite_folder

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^yourwebsite\.example $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

#(2) Inside Folder .htaccess This file is rewriting the subdomain URLs.

http://yourwebsite.example/index.php?siteName=9lessons to http://9lessons.yourwebsite.example

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1

More .htaccess tips: Htaccess File Tutorial and Tips.

#index.php This file contains simple PHP code, using regular expressions validating the subdomain value.

<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
   if($siteNameCheck)
   {
     //Do something. Eg: Connect database and validate the siteName.
   }
   else
  {
    header("Location: http://yourwebsite.example/404.php");
   }
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>

#No Subdomain Folder If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Abdo-Host
  • 2,470
  • 34
  • 33