1-Minute Tutorial: Permanent (301) Redirect via PHP or htaccess
Here is an example of one of the most frequently asked PHP/htaccess-related questions I receive here at Perishable Press:
How do I redirect a specific page/URL using PHP/htaccess?
So common is this inquiry that I have decided to just post a quick, “one-minute” tutorial describing the technique.
Permanent (301) Redirect via PHP
To permanently redirect a page via PHP, place this code before all other content (i.e., at the very top of the document):
<?php // Permanent 301 Redirect via PHP
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://domain.tld/new/location/");
exit();
?>
Once in place, this code will redirect the visitor to the address specified in the third line. Edit that address to match the redirect target and you’re all set. Note: when placed in a header file that is included in multiple web pages, this code will redirect all of them to the specified address.
Permanent (301) Redirect via htaccess
This one is even easier. To permanently redirect a page via htaccess, place this code in your target (e.g., root) htaccess file:
redirect 301 /path/to/old-file.php http://domain.tld/path/to/new-file.php
This is a very common method of permanently redirecting single pages. Once in place, this code will redirect the visitor from the location listed first to the location listed second. Note that the first location is specified relative to the root directory (i.e., the directory in which the htaccess file is found), whereas the second location is specified as the complete URL.
Related articles
- How to Block IP Addresses with PHP
- Temporary Site Redirect for Visitors during Site Updates
- Advanced PHP Error Handling via htaccess
- Advanced PHP Error Handling via PHP
- Permalink Enlightenment
- Compressed CSS Compression
- Perishable Press Triple Loop for WordPress
About this article
This is article #484, posted by Perishable on Wednesday, January 23, 2008 @ 09:09am. Categorized as Function, and tagged with htaccess, php, redirect, tutorial. Updated on January 23, 2008. Visited 11186 times. 6 Responses »
Bookmark • Trackback • Comment • Subscribe • Explore
« 6 Ways to Customize WordPress Post Order • Up • Serve Yourself: Why Feedburner Needs a Feed Fix »
1 • January 23, 2008 at 2:21 pm — Rick Beckman says:
The two-liner call to PHP’s
header()function can be simplified down to one line:header('Location: 'http://www.example.com/', true, 301);The second parameter (
true) determines whether or not that header should replace similar headers which have already been specified; it requires PHP 4.0.4 or newer.The third parameter (
301) is the HTTP status code that should be sent; it requires PHP 4.3.0 or newer.Both the 2nd & 3rd parameters are, of course, optional, but that 3rd parameter is a lot easier to use than crafting extra
header()statements to send the proper HTTP response.