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]<?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’]);
}
?>[/php]

And for www to non-www:

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

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.

2017-09-03T11:38:16+00:00 April 19th, 2014|PHP, Programming|0 Comments

Leave A Comment

*