0

I have a web directory that can be accessed via either http://www.example.com/abc or http://abc.example.com. Same physical directory, same contents, just different addresses.

I want to redirect to abc.example.com if it is accessed via www.example.com/abc. Can I do it by a simple PHP script?

The index.php will be the contents for either address anyway.

2
  • Is there any reason why you particulary want to do this via PHP and not a RewriteRule in .htaccess (or similar)? Having said that I've had to do it via PHP before on a shared IIS server - I couldn't find another way to do it.
    – MrWhite
    Aug 2, 2011 at 19:47
  • I am already using complicated RewriteRules and don't want to bother to jump into those forwarding rules. In addition, there is only one PHP file (index.php) in the directory/domain, so the simpler, the better in this case.
    – Chang
    Aug 2, 2011 at 19:55

2 Answers 2

3

You can analyze the $_SERVER['HTTP_HOST'] variable in PHP:

if( $_SERVER['HTTP_HOST'] !== 'abc.example.com' ){
    header('Location: http://abc.example.com/', true, 301);
    exit;
}

If it's not abc.example.com it will redirect to it.

I guess you can put it into your index.php at the very top.

3

It would be much better to configure the webserver to handle this redirection. It is fairly trivial to configure Apache to do something along these lines. If you are using Apache, look up RewriteRule. Most other web servers have comparable features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.