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?

2
  • 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 8, 2008 at 23:15
  • If you can use wildcard subdomains this can be achieved in .htaccess. See my solution.
    – Dan Bray
    Apr 6, 2016 at 19:05

12 Answers 12

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.

19
  • 1
    Unless each subdomain is served off of a different server, I would thing creating Canonical Name (CNAME) records would be a better plan. en.wikipedia.org/wiki/List_of_DNS_record_types Oct 8, 2008 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 8, 2008 at 17:55
  • @theraccoonbear Assuming you can use wildcards with CNAME as well, that's a thought.
    – Mark Biek
    Oct 8, 2008 at 17:55
  • 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 9, 2008 at 14:02
  • 1
    hi mark, I followed the steps you gave above but the when I do xyz.mydomain.com it redirects to xyz.mydomain.com/cgi-sys/defaultwebpage.cgi... Do I need to do anything else then steps mentioned above ? Apr 1, 2011 at 11:06
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.

1
  • i can not reach httpd.conf file since i am on shared hosting. what can i do? Aug 27, 2016 at 17:25
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.

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.

1
  • 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, 2016 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

1
  • 1
    I am not really sure how to use that.. and in the end, why not to mess up with htaccess?
    – Skuta
    Oct 9, 2008 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
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.

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.

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.

1

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

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.

1
  • Actually, the second step is to configure the web-server Aug 29, 2022 at 6:11
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.