Sign up ×
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 or Same physical directory, same contents, just different addresses.

I want to redirect to if it is accessed via 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

2 Answers 2

up vote 3 down vote accepted

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

if( $_SERVER['HTTP_HOST'] !== '' ){
    header('Location:', true, 301);

If it's not it will redirect to it.

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

share|improve this answer

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

Your Answer


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.