Web Hosting Talk







View Full Version : Script: Subdomain->Domain Redirect


Dan L
12-02-2005, 03:21 PM
<?php
$domain = $_SERVER['SERVER_NAME'];
$data = $_SERVER['REQUEST_URI'];

if(fnmatch('*.*.*',$domain)) {
$domain = explode('.',$domain);
$newDomain = $domain[1].'.'.$domain[2].'/'.$domain[0].$data;

header('Location: '.$newDomain);
} else {
echo 'Could not forward from this URL.';
}
?>

This script takes a subdomain such as 'subdomain.example.com/index.php?a=test' and transforms it into 'example.com/subdomain/index.php?a=test'

This is helpful is you want to have subdomains point to a folder on your main domain.

Note: This does not support TLDs such as '.co.uk', '.com.cn', or any TLDs with two parts.

Korvan
12-05-2005, 02:36 PM
To support those TLDs simply adding a $domain[3] and another .* inside the fnmatch should work.

<?php
$domain = $_SERVER['SERVER_NAME'];
$data = $_SERVER['REQUEST_URI'];

if(fnmatch('*.*.*.*',$domain)) {
$domain = explode('.',$domain);
$newDomain = $domain[1].'.'.$domain[2]'.'.$domain[3].'/'.$domain[0].$data;

header('Location: '.$newDomain);
} else {
echo 'Could not forward from this URL.';
}
?>

Dan L
12-05-2005, 08:42 PM
As far as I know, that would only match .*.* extensions, not .*

Korvan
12-06-2005, 01:14 PM
As far as I know, that would only match .*.* extensions, not .*

Yes, that is correct, it will only support .co.uk and not .com for example.

Also considering peoples main subdomain is usually www you can code it like this for support of both types of TLD's


$domain = $_SERVER['SERVER_NAME'];
$data = $_SERVER['REQUEST_URI'];


$domain = explode('.',$domain);
if($domain[0] != 'www')
{
$newDomain = 'http://www.'.$domain[1].'.'.$domain[2].($domain[3] ? '.'.$domain[3] : '').'/'.$domain[0].$data;
header('Location: '.$newDomain);
echo("You are being redirected to <A HREF=\"{$newDomain}\">{$newDomain}</A>");
exit();
}

//continue page output



This will only work if you use www to access the root of your site.

Dan L
12-06-2005, 10:01 PM
Well the script was originally coded since someone wanted to redirect the same way cPanel does.

The echo is sort of pointless since nothing is output after the header.