How To Detect An Incoming Request (With PHP Script) From a CNAME Subdomain?
Solution 1:
An important distinction to make is that a CNAME and a rewrite/redirect (or vhost) are totally different things that often get confused.
A CNAME is a DNS entity so that you can have multiple names pointing to a singular address. For example, bob.example.com is a host that lives at 1.2.3.4. You can then create a CNAME for alice.example.com which points to bob for DNS resolution and returns the same IP address.
A redirect is an HTTP method to take a request that lands on a certain location (http://bob.example.com/index.html) and returns an instruction to the browser to go somewhere else (http://alice.example.com/somewhereelse.html) which the client's browser shows.
A rewrite is an HTTP method to take a request that lands on a certain location, change it, and then send it on to an answering server without necessarily letting the client's browser know that it's occured.
A virtualhost (vhost, etc...there are different names for the same function) is an HTTP method that allows you to answer a request in different ways by looking at the name that the request is using, often by examining the HTTP Host header that's included in every request. Take the above for example: client requests http://alice.example.com, which resolves via DNS to 1.2.3.4 because alice is a CNAME to bob.example.com. The request lands on the same IP address, 1.2.3.4, but the web server that's running there answers the request with the content under /alice instead of /bob.
Hope that helps
Solution 2:
If you want to do it with PHP, what you'd typically do is to configure your webserver to serve all subdomains to a certain virtual host that runs all requests through a routing PHP script, which will do the redirection. Something like this:
<?php
$map = array(
"try.superman.com" => array(
"/redirect-to-marvel/" => "http://spiderman.com/redirection/redirect-to-marvel/",
),
);
if (isset($map[$_SERVER["HTTP_HOST"]]) {
if (isset($map[$_SERVER["HTTP_HOST"]][$_SERVER["REQUEST_URI"]])) {
header("Location: " . $map[$_SERVER["HTTP_HOST"]][$_SERVER["REQUEST_URI"]]);
exit;
}
}
header("Location: http://spiderman.com/404.php");
There is a lot of room for improval, including doing all of this just with mod_rewrite (or the equivalent of your webserver, but I am assuming you are using Apache here, since you are mentioning .htaccess
).
With PHP you have the flexibility to query a database for the proper redirection.