PHP Redirect 301 permanently

Sometimes you might want to redirect your visitors to a new URL address. This article will show you how to make a PHP redirect using the 301 "moved permanently" redirection. This is the one you should use as it is the most search engine friendly. Like the name suggests, PHP redirect tells the browser (or a search engine bot) that the page has been permanently moved to a new location.

A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);
// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");
// 303 See Other
header("Location: /foo.php",TRUE,303);
// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

PHP Redirect Code

To redirect people and robots to a new location use this PHP redirecting code:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com");
?>

Tip: use lower-case name for the header function (not Header) to make sure your PHP redirect code is compatible with PHP 6.

You could skip the 301 Moved Permanently tag and use just:

<?php
header("Location: http://www.New-Website.com");
?>

But this would result in a "302 Moved Temporarily" redirect instead of a 301 one. This should be avoided as permanent redirects are more search engine friendly and should be used where possible.

You can enter any sub-page for the location, this PHP code will redirect users to the test.php sub-page of your website:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com/test.php");
?>

It is important that you don’t have any other code (including empty rows and spaces) before the above PHP redirect code. If you do you will get a nice headers already sent notice from PHP and the redirect will not work.

That’s it! Enjoy redirecting PHP pages.

HTTP 301 Redirect in PHP

<?php
// Permanent redirection
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.somacon.com/");
exit();
?>

If you set the Location header by itself, PHP automatically sets the status code to HTTP/1.1 302 Found.

Note, if you attempt to send headers after content has been sent, you will get a warning like, "Warning: Cannot modify header information – headers already sent by …". Watch out for empty lines and spaces between PHP open and close tags. ASP ignores these, but PHP does not.

Leave a Reply