HTTP redirects are a method for web servers to direct clients from one url to another. These can be used for temporarily handling errors / downtime, redirecting http to https, migrating from one domain to another, changing url schemes, etc. In its simplest form a HTTP redirect is a combination of a status code and the Location
header. We will create some common HTTP redirects with Undertow.
Redirect Example
We will be working with the following web server containing a few simple routes to demonstrate each type of redirect.
Hello Handler
All endpoints will redirect to the hello handler which simply outputs the text Hello
.
Temporary Redirect (302)
The temporary redirect is one of the most commonly used redirects and as it's name states it is meant to be temporary. There are many applications of the temporary redirect. Some common uses are redirecting to error pages, redirecting you back to your previous page after a form submission, and redirecting unauthenticated users to a login page.
Permanent Redirect (301)
The permanent redirect works very similarly to the temporary redirect with the added implication that this redirect is permanent. This implication can be used by clients in various ways. One of the most common is web crawlers updating their indexes based on 301s. If you decide to update your domain name, redirect from http to https, or change your url scheme, the 301 redirect allows you to keep your old links active but tell the crawlers they should start using the new link instead. This is one of the primary ways to make sure Google starts listing your results under the new urls.
Referrer Redirect Helper
Although server side rendered websites are becoming less popular and being replaced by single page apps they are still a great tool for many use cases. In server side rendered web pages many actions trigger form POST requests which then need to redirect the user to another page when it completes. This is a helper intended to dynamically redirect back to the page the request was made from based on the Referer
header. Yes the Referer header was misspelled in the HTTP spec and has stuck around that way.