Redirection using PHP

If you ever need to do a redirect in PHP code, make sure that you do more than just the default – ie not just the R, but the R=301 in the htaccess, or not only the “Location”, but also the initial 301 Moved Permanently code. The default redirect is a non search engine friendly 302 temporary redirect.

A 301 redirect is a search engine safe way redirecting traffic.

This PHP code must appear before any output is sent to the browser.


if (PHP_VERSION >= ‘4.3.0’)
header(“Location: $url”, 0, 301);
else if ($sapi == ‘cgi’ OR $sapi == ‘cgi-fcgi’)
header(“Location: $url”);
// Call the status header after Location so we are sure to wipe out the 302 header sent by PHP
header(‘Status: 301 Moved Permanently’);
header(“Location: $url”);
header(‘HTTP/1.1 301 Moved Permanently’);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s