Home About Us Services Portfolio Articles Reference Contact

PHP 301 Redirect & PHP Canonical Redirect

How to properly redirect in PHP for a 301 Moved Permanently or non-www to www or a canonical redirect in PHP:

PHP 301 Redirect

Single Page Redirect:

Place the following script at the very top of the page that you would like redirected permanently.  Replace the red “new-url” with your own:

<?php
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: http://www.new-url.com/’);
?>

If you need to direct one php page to a different php page:

<?php
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: http://www.new-url.com/newpage.php‘);
?>

PHP Canonical Redirect:
(non-www to www)

To resolve the issue of non-www to www in a domain name, use the following PHP script at the top of the page file:

<?php
if (substr($_SERVER['HTTP_HOST'],0,3) != ‘www’) {
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: http://www.’.$_SERVER['HTTP_HOST']
.$_SERVER['REQUEST_URI']);
}
?>

Leave a Reply