How to manage wildcard subdomains in PHP?

Wildcard subdomains are used for user specific sites, Deviantart, are good examples. Usually DNS handles the subdomains depending on A and CNAME records.

Using .htaccess will give control on incoming trafic (URL translation). Below .htaccess code will redirect any subdomain to PHP page.

RewriteCond %{HTTP_HOST} !^www\.domain\.com
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com [NC]
RewriteRule ^/?$ /member.php?username=%1 [L]

.htacces code will forward incoming request to member.php with GET method. So anyone who types will get content of By using SQL query you can verify if the username exists or not.

$sth = $dbh->prepare("SELECT * FROM user WHERE username=:username");
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$result = $sth->fetch(PDO::FETCH_ASSOC);
if ($result) {
    // show user data
} else {
    // show 404 page

Found a typo? Something wrong with this content?

Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all contributors.