Redirect Using .htaccess or PHP

November 5, 2008

There are a few ways to redirect visitors to your website using either PHP or .htaccess and neither take preference over an other in my book, no doubt some geeky programmers will jump up and done saying one method takes 3 thousands of a second more to execute.

PHP Method
<?php
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location:
http://www.new-url.com” );
?>

This looks simple and it is, just a couple of things to remember:-
This code most come before any call to output to the browser, that means it must precede any text, images, even a space, if it doesn’t you will get an error.
Simple redirect using .htaccess file
Redirect 301 /oldpage.html http://www.example.com/newpage.html

The first section tells the Apache what to do and what HTTP Header Status to use, the next is the old page and the final chunk is the nice new shinny file that we want to send people too.
Mod_rewrite method in the .htaccess file
rewriteEngine on
rewriteRule ^oldpage\.php$
http://www.mywebsite.com/newpage.php [R=301,L]

The first line tells Apache to switch the mod_rewrite on.
The second line instructs mod_rewrite to match the request where the URI is exactly oldpage.php. The ^ matches the beginning and the $ matches the end of the expression, a the \ is used to escape the period, if we left the \ out the period would have become a meta character and matched any character, the R=301 means send HTTP Status Code 301 and the final L means LAST, in other words don’t process any other rules.


Entry Filed under: PHP. Tags: , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Follow us on Twitter

Categories