This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

If you are changing your URL structure, for example when moving to a search engine friendly URLs system, you need to be able to let Google and all the other search engines that the page has moved to the new URL. You really don’t want to display the same content on two URLs

So to achieve this we can do what is called a 301 redirect. This is a special redirect message which basically says “has permanently moved to”. By doing this, all of the search engine power, rank or whatever you want to call it will be directly transferred to the new URL.

However

Sometimes your script might spit out the headers earlier than you expect. If this happens then your site will fail completely to load with a fatal error along the lines of

warning: Cannot modify header information – headers already sent by (output started at .

We really don’t want this to happen, so what we can do is wrap the redirection in a headers_sent check and then fall back to a javascript redirect if headers have been sent for some reason. This is belt and braces logic.

Note script tags need spaces removing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function requrl_check($correct_url, $delay=3){
  $request_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  if($request_url != $correct_url){
      if(!headers_sent()){ //going to assume that headers are not sent
      header("HTTP/1.1 301 Moved Permanently");
          header('location: ' . $correct_url . '');
          exit();
      }else{
          echo "<h3>The Page $request_url has Moved</h3>
             <a href=$correct_url>$correct_url</a>";
          echo '<h3>Now Refreshing in ' . $delay . ' Seconds</h3>Refreshing to:<br>' . $correct_url . '<s c r i p t type="text/JavaScript"><!--
     setTimeout("location.href = \'' . $correct_url . '\';",' . ($delay * 1000) . ');
     --> </s c r i p t>';
          exit();
      }
  }
}

tidy :–)

Further Reading: www.stuntdubl.com www.intertwingly.ne webgasm.actiononline.biz www.techcounter.com www.chiropractichomepage.com 123howtoguide.com searchblog.tamar.com