Monday, May 05, 2008

HTTP Redirect : Do it the right way !

There are two ways to redirect a user to a different page:
A) Server redirect : This is where server notifies the client in HTTP Response header that the page has been moved somewhere else. This is done by sending one of following response status code in response Header

  • Permanent Redirect (301)
  • Temporary Redirect (307)
  • Undefined redirect (302)
Here client do not need to get the body of the response before redirecting. In this method when a client contacts server for a document the server itself, configured to redirect the document to another address, replies to the client that it should instead look at the new address. Examples:
JSP/Servlet: response.sendRedirect("PATH_TO_NEW_RESOURCE");
print "Status: 301 Moved Permanantly\n";
print "Location: PATH_TO_NEW_RESOURCE\n\n";
Apache mod_rewrite:
rewriteEngine on
rewriteRule OLD_PATH PATH_TO_NEW_RESOURCE [R=permanent,L]

B) Client redirect : This is done in HTTP response body as opposed to the HTTP response header. This can be done either by HTTP META Header tag:
Or using JavaScript:
<script type="text/javascript"> window.location.href='PATH_TO_NEW_RESOURCE'; </script>

Here the client need to download the full body of the response, look for refresh instruction or Javascript code block and then proceed for new address.

Clearly you should use Method A (Server Redirection), Disadvantages of using Method B are:
1) It causes Browsers to flickr and refresh as the old page is loading.
2) The Meta tag could really break the Back button, You would have faced this problem with many pages, after clicking the back button and it keeps coming to the same page. Braking the back button is really a sin from UI design perspective, it is the second most used browser feature and you don't want to break it. User can get really annoyed with this, close the window, and may not visit your site.
3)The HTTP status code of the page will remain 200, most search engines will continue to think the location is valid. Any page rank of the old location will not be transferred to the new location.

Moreover in Method A the server also gives some information about the purpose and type of redirection, which allows the Client to behave differently depending on the type of redirect (302, 307 or 301).

No comments: