How to redirect clients from http to https?

129 views
Skip to first unread message

mathias

unread,
Oct 9, 2015, 9:34:09 AM10/9/15
to vert.x
I use the following code (a server verticle listening on port 80):

 router.routeWithRegex(".*").handler(routingContext -> {
 
String absoluteURI = routingContext.request().absoluteURI();
 
String redirectUrl = DEFAULT_URL;
 
if (absoluteURI.startsWith("http://")) {
   redirectUrl
= "https" + absoluteURI.substring(4);
 
}
 
HttpServerResponse response = routingContext.response();
 response
.setStatusCode(HttpURLConnection.HTTP_MOVED_TEMP);
 response
.putHeader("Location", redirectUrl);
 response
.end;
}

It redirects all clients requesting "http://mydomain.com/mypath" (implicit port) to the correspondong SSL server (https + port 443)
But it does not work for clients requesting "http://mydomain.com:80/mypath" (explicit path).
It looks to me that browsers do not change explicit ports when redirecting to a https URL.

How to redirect clients correctly to SSL which works for both cases (explicit and implicit ports)?

Paulo Lopes

unread,
Oct 9, 2015, 9:43:04 AM10/9/15
to vert.x
If your clients are we browsers and you know that they are more or less up to date, no IE6 or something like that...

You can use HSTS, in your HTTP handler always add the header:

Strict-Transport-Security: max-age=31536000; includeSubDomains;.

This will tell browsers to only connect in HTTPS to your app and they should remember it for alteast 1 year, you can change this value in the max-age.

However if you're not running on default ports of course your browser cannot guess where the https port is listening so it only works for 80 -> 443

Otherwise you need to parse the URI and replace ports and protocol...

Alexander Lehmann

unread,
Oct 9, 2015, 10:19:16 AM10/9/15
to vert.x
If you are building your redirect URL, you have to account for the :80, if it is present in the URL, a URL like https://domain:80/ is valid unfortunately so the browser cannot do anything smart.

If you want to keep the explicit port, you could so something like replaceAll(":80",":443") as a hack.



On Friday, October 9, 2015 at 3:34:09 PM UTC+2, mathias wrote:

mathias

unread,
Oct 9, 2015, 4:28:01 PM10/9/15
to vert.x
Alright, thank you!

Now I am parsing the URL and checking for the port.
Reply all
Reply to author
Forward
0 new messages