Permanent (301) Redirects with PHP
If you want to permanently redirect a small number of URIs, or redirect based on conditions defined in PHP, then you need a permanent PHP redirect.
To redirect clients based on things like screen resolution or window size, you should use javascript redirects.
For most situations where you want to send visitors elsewhere, a server side (HTTP) redirect is usually the best choice. The use of mod_alias and mod_rewrite (on Unix servers), perhaps within a htaccess file, are often the best methods of accomplishing server-side redirects. You can`t beat mod_rewrite for flexibility.
Unfortunately, not everyone has access to these modules, and in any case you may need to do some PHP processing before performing the redirect.
A basic permanent (301) redirect in PHP uses the code below:
<?php
// This header tells the client the HTTP status code of the page
header("HTTP/1.1 301 Moved Permanently");
// The client must then be informed where the URI is now located
header("Location: http://www.example.com/example");
exit();
?>
If the HTTP status code is not specified, then the redirect will automatically result in a 302 code (saying the the page has been 'found' or in other words has only moved temporarily). Unless you want clients (and search engines) to continue using the previous URI, then you need to specify the status.
Once you've written your redirect, you can check that it has worked properly using the handy dandy HTTP Status Code Analyser.
30.03.2007. 18:46
Paul said on 20.10.2008. 13:01
when a website has been built is it reasonable to expect a 301 redirect to be in place before it is handed over to the customer
Andy said on 20.10.2008. 15:54
Can you clarify? Do you mean a redirect from a development server to the final location?
Niki said on 18.12.2008. 15:19
Whatz the difference..
301 Redirect with Location header
or
direct Location header specified in a PHP script causing a 302 redirect.
Does it concern security or what differs bw them..Please let me know.
Andy said on 18.12.2008. 19:42
It's a technical difference. A 302 is an "unknown" redirect, which means that the browser should continue to request the original URL. A 301 is a permanent redirect.
A 302 => B
...means keep asking for A
A 301 => B
Means don't ask for A any more, ask for B
The most common reason to use a 301 is because a search engine will update it's database with your new URL (and give you credit for links to the old URL). This won't happen with a 302.
More info on status codes at: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3
Recent Responses:
Page last (manually) updated: December 23, 2009.
Questions, comments, insults or praise? Have your say: