Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

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.

share|improve this question
    
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. –  w3d Aug 2 '11 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. –  FEQ Aug 2 '11 at 19:55
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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