Buat Subdomain Dinamis menggunakan PHP dan Htaccess
(1) Root .htaccess
File ini adalah pengalihan http://www.yourwebsite.com ke http://yourwebsite.com untuk penggunaan beranda. Semua pengalihan subdomain ke yourwebsite_folder
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^yourwebsite\.com $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
(2) Di dalam Folder .htaccess
File ini menulis ulang url subdomain.
http://yourwebsite.com/index.php?siteName=9lessons
ke
http://9lessons.yourwebsite.com
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1
Lebih banyak .htaccess tips: Tutorial dan Tips File Htaccess.
index.php
File ini berisi kode PHP sederhana, menggunakan ekspresi reguler yang memvalidasi nilai subdomain.
<?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.com/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>
Tidak Ada Folder Subdomain
Jika Anda menggunakan direktori root (htdocs / public_html) sebagai direktori proyek, gunakan file .htaccess berikut ini.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1