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(preg_match(“/[index.php]$/”,$_SERVER[REQUEST_URI]))
{

$url=”http://”.$_SERVER[HTTP_HOST].preg_replace(“/(index.php)$/”,””,$_SERVER[REQUEST_URI]);
$sapi=php_sapi_name();
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’);
}
else
{
header(“Location: $url”);
header(‘HTTP/1.1 301 Moved Permanently’);
}
}

Reference:
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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