You need to do a correct header call.
Like this:
if(strpos('sub.example.com', $_SERVER['HTTP_HOST']) !== false){
header("location: http://example.com/sub/");
}
EDIT:
Based on the information in this post:
You can also use this function instead:
function get_subdomain($url=""){
if($url==""){
$url = $_SERVER['HTTP_HOST'];
}
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['path']);
$subdomains = array_slice($host, 0, count($host) - 2 );
return implode(".", $subdomains);
}
if('sub' != get_subdomain()){
header("location: http://example.com/sub/");
}