Virtual hosting is a method which allows a single server (or multiple) to listen on a single port (most often the default port 80
) and serve different content based on the host / domain name. This is is commonly used in load balancers or web servers such as NGINX or apache to serve several websites from a single server. In its simplest form virtual hosting is a pair of a port and hostname that map to a handler.
Virtual Hosting in Undertow
One of the most common virtual hosting use cases is redirecting a non www domain to a www domain. Creating custom HttpHandler's in Undertow is easy. Undertow also has a built in virtual hosting handler called NameVirtualHostHandler
.
Routes
A simple hello world route and a route to redirect to the given hostname. We are not just redirect blindly to the new host we are capturing the full path and any query params as well. This is made easy using some OkHttp
classes.
Get Current URL
Here is our simple util method to grab the current HttpUrl
. We use OkHttp's
library here because they have a very nice api for working with urls.
Adding Handlers to NameVirtualHostHandler
Here we add two virtual hosting handlers. One on localhost which should redirect to www.localhost just as an example (This will work in some browsers but not with cURL
). The second handler is our actual web content.
Testing it out
Now cURL
won't resolve www.localhost unless we add it to our hosts file however Chrome and some other browsers will. This is just an example and would generally use a real domain instead of localhost. Let's also make sure we preserve the path and query params.