Redirect HTTP requests to HTTPS

This feature will make all the affected HTTP calls perform a redirect to itsHTTPS counterpart before processing the call.

By default the redirection is a 301 Moved Permanently,but it can be configured to be a 302 Found redirect.

This feature is defined in the class io.ktor.features.HttpsRedirect and no additional artifacts are required.

Usage

  1. fun Application.main() {
  2. install(HttpsRedirect)
  3. // install(XForwardedHeaderSupport) // Required when behind a reverse-proxy
  4. }

The code above installs the HttpsRedirect feature with the default configuration.

When behind a reverse-proxy, you will need to install the ForwardedHeaderSupport or the XForwardedHeaderSupportfeature, for the HttpsRedirect feature to properly detect HTTPS requests.

Configuration

  1. fun Application.main() {
  2. install(HttpsRedirect) {
  3. // The port to redirect to. By default 443, the default HTTPS port.
  4. sslPort = 443
  5. // 301 Moved Permanently, or 302 Found redirect.
  6. permanentRedirect = true
  7. }
  8. }

Testing

Applying this feature changes how testing works.After applying this feature, each handleRequest you perform, results in a redirection response.And probably this is not what you want in most cases, since that behaviour is already tested.

XForwardedHeaderSupport trick

As shown in this test,you can install the XForwardedHeaderSupport feature and add a addHeader(HttpHeaders.XForwardedProto, "https")header to the request.

  1. @Test
  2. fun testRedirectHttps() {
  3. withTestApplication {
  4. application.install(XForwardedHeaderSupport)
  5. application.install(HttpsRedirect)
  6. application.routing {
  7. get("/") {
  8. call.respond("ok")
  9. }
  10. }
  11. handleRequest(HttpMethod.Get, "/", {
  12. addHeader(HttpHeaders.XForwardedProto, "https")
  13. }).let { call ->
  14. assertEquals(HttpStatusCode.OK, call.response.status())
  15. }
  16. }
  17. }

Do not install the feature when testing or uninstall it

Uninstalling it:

  1. application.uninstall(HttpsRedirect)

Prevent installation in the first place:

  1. // The function referenced in the application.conf
  2. fun Application.mymodule() {
  3. mymoduleConfigured()
  4. }
  5. // The function referenced in the tests
  6. fun Application.mymoduleForTesting() {
  7. mymoduleConfigured(installHttpsRedirect = false)
  8. }
  9. fun Application.mymoduleConfigured(installHttpsRedirect: Boolean = true) {
  10. if (installHttpsRedirect) {
  11. install(HttpsRedirect)
  12. }
  13. // ...
  14. }

In this case, you can also have a separate test that calls mymodule instead of mymoduleForTesting to verifythat the HttpsRedirect feature is installed and other things that you are not doing in tests.

I get an infinite redirect when using this feature

Have you installed the XForwardedHeaderSupport or the ForwardedHeaderSupport feature?Check this FAQ entry for more details.