e premte, 21 shtator 2007

301 redirection with PHP

Using the PHP header function, it is possible to do 301 redirection.

To forward www.mywebsite.com to mywebsite.com, use the following code:

if(stristr($_SERVER["HTTP_HOST"], 'www')){
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://mywebsite.com/" . $_SERVER["REQUEST_URI"]);
exit();
}
?>

To forward mywebsite.com to www.mywebsite.com, use the following code:

if(!stristr($_SERVER["HTTP_HOST"], 'www')){
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.mywebsite.com/" . $_SERVER["REQUEST_URI"]);
exit();
}
?>

Remember to replace 'mywebsite.com' with your correct website domain name :)

Some things worthy of notice:

  • Notice how we send the HTTP 301 header and then we immediately follow it with the new location.
  • Also, notice that we forward the REQUEST_URI value. The REQUEST_URI is the path within the website to the web page. For example, in http://ekstreme.com/phpcounter/index.php, the /phpcounter/index.php part is the REQUEST_URI. Our forwarding code above forwards to the user to the page they requested.
  • Notice the exit() statement: this makes sure that the PHP code following this code does not get executed and that only the forwarding information is sent to the browser.

This code is best used for single pages that require forwarding, and not whole websites. To use it, just add the code at the very beginning of the page's PHP file. Make sure there are no spaces or any other characters before the opening , otherwise, the code won't work and you'll get a warning.

Nuk ka komente: