Redirects in PHP – Easy Methods for Temporary and Permanent Redirections

Redirecting an old page to a newer, or a domain to another domain, is easy in PHP and can be done using header() function.

The main consideration in redirection is HTTP status code. 301 is the permanent redirect, while 302, 303, and 307 are temporary redirects. By default PHP Location header() redirection method sends 302 status code, which is a temporary redirect and does not transfer page rank and link juice to the new URL. In order to get Google transfer the page rank and link juice, we need to make sure we are using Permanent redirection. Here are the codes for common methods used in redirection.

Method 1: Default

header("Location: http://www.domain.com/directory/file.html");
exit();

Method 2: Manually Defining Header

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.domain.com/directory/file.html");
exit();

Method 3: Response Code Parameter

// 301 Moved Permanently
header("Location: /directory/file.html",TRUE,301);
exit();
// 302 Found
header("Location: /directory/file.html",TRUE,302);
exit();

Note: You must always use exit(); or die(); after redirection code to avoid php executing any further code and resulting in errors.

Final Thoughts

Method 2 and Method 3 are stable for using in pages you care for backlinks and pagerank transfer. If you have any other method, or anything to object, your comments would be highly appreciated.