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
wildcard subdomains
this can be achieved in.htaccess
. See my solution.