PHP 301 redirect for non-www to www urls

Want to do a 301 redirect for non-www urls to www, simply use php header command like the following syntax:

<?php
if ($_SERVER['HTTP_HOST'] != 'www.abc.com'){
    header("HTTP/1.1 301 Moved Permanently", true, 301);
    header("Location: http://www.abc.com".$_SERVER['REQUEST_URI']);
}
?>

And for www to non-www:

<?php
if ($_SERVER['HTTP_HOST'] != 'abc.com'){
    header("HTTP/1.1 301 Moved Permanently", true, 301);
    header("Location: http://abc.com".$_SERVER['REQUEST_URI']);
}
?>

This is extremely useful, where you don’t want to use .htaccess file. But remember to put the code on all pages where you actually required the redirect.

19. April 2014 by Adnan
Categories: PHP, Programming | Tags: , , | Leave a comment

Leave a Reply

Required fields are marked *


*