How to Redirect a Web Page


This post describes how to properly redirect a web page using an HTTP 301 status code and Location header. The 301 status code is used to indicate that a page has permanently moved. 301 redirect is the most efficient and Search Engine Friendly method for webpage redirection. PHP redirect tells the browser (or a search engine bot) that the page has been permanently moved to a new location.
<?php
// Permanent redirection
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.new-domain.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 ...". Look for empty lines and spaces between PHP open and close tags.

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

You can redirect the page to new location along with parameters; this PHP code will redirect users to new location along with its query string:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.new-domain.com".strtolower($REQUEST_URI));
exit();
?>

Comments

Popular posts from this blog

Detecting user's screen size and resolution

autoload class

MySql Slow Queries