Hi,
This is untested and will need some tweeking for the right order of nested commands, but should give you the basic feel of it:
$calledurl = $_SERVER['HTTP_HOST'];
directory = array_reverse(explode ($calledurl, "//"));
$page = directory[0].".php";
$redirecturl = "somedomain/somelocation/".$page;
Header("Location: $redirecturl\n");