PHP: Redirection Overview
This post is more for me than for somebody else, because it will let me keep the posted information handy. WordPress is written in PHP and I have to recall this script language when I need to alter some iNove theme scripts. This time I craved for adding redirection to some script. The easiest way is to utilize code like the following:
header( "HTTP/1.1 301 Moved Permanently" ); // this line is optional and can be skipped header( "Location: http://dotnetfollower.com" );
Using header(“Location: some new url“) method we can transfer user to a new page. Under the hood header() asks browser to make another request for another url. Note that the header() must be called before any text (e.g. HTML tags, blank lines, something forwarded by PHP echo function and so on) is sent to the user browser, otherwise it will not work. That is the major limitation of the given approach we have to be aware of.
The first line of the code sample above sends the redirect response code to the browser. Redirect response code is considered as a reason of redirection. You can skip the sending of redirect code. But if you delete or move page to another location, I insistently recommend to send a relevant code, because such codes are being analyzed practically by all Search Engines. Including, of course, the evident leader – Google Search Engine, which examines such codes very thoroughly. The Google PageRank of a page you redirect to can directly depend on the redirect code you return. For instance, in example above I return 301, which means that page was moved permanently to another location that is pointed out in the second line of code. The code 301 also tells Search Engines that link value of the requested url has to be given to the new one. In theory, the new page inherits PageRank of the requested (but absent at the time) page. In reality, it happens not instantly, but some time later.
Redirect response codes are a subset of status codes available in HTTP 1.1. The complete HTTP 1.1 specification is accessible in RFC 2616. The first digit of the status code defines the category of response. The status codes are grouped into five categories:
-
100s – informational, indicate that request is received and is being processed. For example,
- 100 Continue;
- 101 Switching Protocols and etc.
-
200s – success, indicate that request was successfully received, understood, and accepted. For example,
- 200 OK;
- 202 Accepted and etc.
-
300s – redirection, indicate further action must be taken in order to complete the request, because a requested resource has been moved. Response Http-header usually includes a Location header indicating the new address. For example,
- 301 Moved Permanently;
- 303 See Other and etc.
-
400s – client error, indicate that request contains bad syntax or cannot be fulfilled. For example,
- 400 Bad Request;
- 401 Unauthorized;
- 404 Not Found;
- 408 Request Time-out and etc.
-
500s – server Error, indicate that server failed to fulfill an valid request. For example,
- 500 Internal Server Error;
- 502 Bad Gateway;
- 503 Service Unavailable and etc.
Evidently, the most applicable category for redirection is a 300s status code. The full list of available status codes of this category is presented below:
- 300 Multiple Choices;
- 301 Moved Permanently;
- 302 Found;
- 303 See Other;
- 304 Not Modified;
- 305 Use Proxy;
- 307 Temporary Redirect;
OK, let’s revert to the changes I made in one of the iNove theme scripts. Some external sites have the corrupted links to one of my articles – Silverlight for Windows Phone 7: How to bind UserControl to itself. These bad links look like ‘http://dotnetfollower.com/wordpress/2011/06/silverlight-for-windows-phone-7-how-to-bound-usercontrol-to-itself/">http://dotnetfollower.com/wordpress/2011/06/silverlight-for-windows-phone-7-how-to-bound-usercontrol-to-itself/</a>‘. As you can see, such link doubles the required url and contains a few improper symbols (quotes and Html-tags). Of course, when somebody goes through the link he receives 404 Not Found error. I decided to change 404.php so that it directs user to valid url of the article if the initial requested url contains substring ‘silverlight-for-windows-phone-7-how-to-bound-usercontrol-to-itself’. The changes are below:
<?php $request=$_SERVER['REQUEST_URI']; $pos = strpos($request, 'silverlight-for-windows-phone-7-how-to-bound-usercontrol-to-itself'); if ($pos !== false) { header( "HTTP/1.1 301 Moved Permanently" ); header( "Location: http://dotnetfollower.com/wordpress/2011/06/silverlight-for-windows-phone-7-how-to-bound-usercontrol-to-itself/" ); exit(); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> <title><?php bloginfo('name'); ?><?php wp_title(); ?></title> ... <!-- some text is skipped --> </head> <body> <div id="container"> ... <!-- some text is skipped --> <div id="notice"> <h1><?php _e('Welcome to 404 error page!', 'inove'); ?></h1> ... <!-- some text is skipped --> </div> <div class="fixed"></div> </div> </body> </html>
Note again, the redirecting is in the beginning of the file in order to prevent sending any text to the browser. That’s important.
OK then, let’s find out what alternative ways to make redirect we have.
The first alternative I know is an usage of Html-tag meta with an attribute http-equiv=”refresh”. Meta refresh is a legacy approach, which instructs a web browser to refresh the current page (or frame) after a certain interval. In addition it can prompt the browser to go to a different url during the next page refreshing.
<meta http-equiv="refresh" content="5; url=http://dotnetfollower.com">
Or
echo '<meta http-equiv="refresh" content="5; url=http://dotnetfollower.com">';
The meta-tag redirects a browser to http://dotnetfollower.com after 5 seconds. Meta-tag has to be placed only inside the <head></head> region of Html markup. Inside other tags (e.g. <body></body>) it will be ignored. I think it’s a quite serious limitation.
The second alternative is a JavaScript redirect:
<script language="javascript"> window.location.href='http://dotnetfollower.com'; </script>
Or
echo '<script language="javascript">'; echo 'window.location.href="http://dotnetfollower.com";'; echo '</script>';
This code makes browser go to another page. Such script-tag can be placed inside either the <header></header> or <body></body> regions of Html. It’s unlikely, but the JavaScript support can be turned off in browser. Obviously, in this case JavaScript redirection is unable to work as well.
So, let’s show a summary table:
Redirect method | Description | Limitations |
Location header | Sends a raw HTTP Location header to redirect a browser to a location different than requested url. It may follow the sending of a redirect response code, which acts as a reason of redirection | Must be called before any actual output is sent |
Example
header( "Location: http://dotnetfollower.com" ); // directs user to the new location
Meta refresh | Redirects a browser to a new location after a certain amount of seconds | Has to be placed inside the <head></head> Html tags |
Example
<meta http-equiv="refresh" content="5; url=http://dotnetfollower.com"> <!-- Directs the browser to the new location after 5 seconds -->
JavaScript redirect | This code makes browser start loading another page | Can be placed inside the <header></header> or <body></body> Html tags. It requires the JavaScript support is turned on in client browser |
Example
<script language="javascript"> window.location.href='http://dotnetfollower.com'; </script>
PS There is a function http_redirect. It’s a part of the PECL extension to PHP. Of course, to use http_redirect the extension has to be installed. I believe http_redirect uses Location header as well.
If you know other redirection methods in PHP, please don’t hesitate to reveal it here in the comments.