7. Redirection

HTTP allows servers to redirect a client request to a different location. Although, this will usually result in another network round trip, it has some useful applications:

  • A web application may use redirection to navigate between parts of the application.
  • If content has moved to a different URL or domain name, redirection can be used to avoid breaking old URLs or bookmarks.
  • It is possible to convert a POST request to a GET request using redirection.
  • A client can be directed to use its local cache for content that has not changed.

A server specifies redirection by returning a 3xx status code:

301

This indicates that the content now resides permanently at the location specified by the Location header and future requests should be directed to this location.

302

Same as 301, except that the new location is temporary and future requests should still be sent to the original location. Another feature of this status code is that if the original request was a POST the client will change to using a GET when it re-issues the request (See below for more details).

303

This status code was intended to be the only status code that caused a POST to be converted to a GET. However, most browsers treat a 302 like a 303.

304

Used in response to an If-Modified header to redirect a request to the browser's local cache.

305

A 305 response is used to specify that a request must be resubmitted through the HTTP proxy in the Location header

Redirecting POST requests

In certain situations, interactive web applications must use POST requests (see 6. Methods). However, this causes a problem with the resulting web page. If the user attempts to refresh the page they are presented with a message box asking them whether they want to retry the previous action. Another problem is that page may have been marked as not cacheable for security reasons. If the user clicks the Back button and encounters a non-cacheable page resulting from a POST the following is displayed in IE (if you have disabled Friendly HTTP Messages):

Expired Page

These problems can be avoided by redirecting the result of a POST to a GET using a 302 status code. (See the example below)

Example 7

Redirecting a POST

This is one of the samples from Example 6 that has been modified to redirect the result of the POST request. If you refresh this page after modifying the account balance, there is no retry message box displayed and the account balance will not change:

Account Balance = $1000

Amount to debit: $

     

Using HttpWatch with Example 7

To view the HTTP headers discussed on this page:

  1. Open HttpWatch by right clicking on the web page and selecting HttpWatch from the context menu
  2. Click on Record to start logging requests in HttpWatch
  3. Click on the Submit button above
  4. You'll see a POST 302 entry that redirects to a GET on this page.
<  6. HTTP Methods8. Compression  >

Ready to get started? TRY FOR FREE Buy Now