PHP redirect function (301 / 302)

I'm often asked how to do 301 redirects in PHP. It's not hard, but it's a pain having to remember the exact syntax every time. Here's a little function I wrote for Jojo CMS for making redirects easy.

Usage

Add one line of code whenever you need to do a redirect.

301 redirects...

redirect('http://www.domain.com');
or
redirect('http://www.domain.com', 301);

302 redirects...

redirect('http://www.domain.com', 302);

The function

You will need to include this code in your PHP script to be able to use this redirect function.
function redirect($url, $type=301)
{
if ($type == 301) header("HTTP/1.1 301 Moved Permanently");
header("Location: $url");
echo 'This page has moved to <a href="'.$url.'">'.$url.'</a>';
exit();
}

Jojo users

This function is available as part of Jojo CMS. Simply place "Jojo::" before the function call eg...
Jojo::redirect('http://www.domain.com');

Not so hard

There we go. A little function that makes a reasonably simple job very simple. It's saved me lots of time having to remember the exact syntax for a 301 redirect.

Feel free to send a link my way if you find this useful.
Digg StumbleUpon del.icio.us technorati blinklist furl reddit sphinn

Related Articles

Tags: 301 redirect 302 redirect 301 redirection 302

Comments

Alex Mielus - May 11, 2008

There's no need to remember the exact syntax every time. I always start a site with a predefined .htaccess that is saved on my email :) ... which include this:

<code>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
</code>

Haiming - A+ SEO Services - May 19, 2008

Hi Harvey,

I use Joomla for my website, where should I put the code in the php files? I know a little bit php and html, but not a php programmer. Can you explain it a little bit in detail?

By the way, it was very nice to meet you on Search Master siminar today. thank very much you for help!

Haiming

PHP Redirect Tutorial - May 22, 2008

i used it in my web site .... thank you

Post Comment

Post Comment

*
*


Visual CAPTCHA

*
Code is not case-sensitive
*

We welcome comments on this article, provided they have something to contribute. Please note that all links will be created using the nofollow attribute. This is a spam free zone. HTML is stripped from comments, but BBCode is allowed.