Ktor 1.6.3 Help


The HttpsRedirect plugin (previously known as feature) will make all the affected HTTP calls perform a redirect to its HTTPS 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.


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

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


fun Application.main() { install(HttpsRedirect) { // The port to redirect to. By default 443, the default HTTPS port. sslPort = 443 // 301 Moved Permanently, or 302 Found redirect. permanentRedirect = true } }


Applying this plugin changes how testing works. After applying this plugin, 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 plugin and add a addHeader(HttpHeaders.XForwardedProto, "https") header to the request.

@Test fun testRedirectHttps() { withTestApplication { application.install(XForwardedHeaderSupport) application.install(HttpsRedirect) application.routing { get("/") { call.respond("ok") } } handleRequest(HttpMethod.Get, "/", { addHeader(HttpHeaders.XForwardedProto, "https") }).let { call -> assertEquals(HttpStatusCode.OK, call.response.status()) } } }

Do not install the plugin when testing or uninstall it

Prevent installation in the first place:

// The function referenced in the application.conf fun Application.mymodule() { mymoduleConfigured() } // The function referenced in the tests fun Application.mymoduleForTesting() { mymoduleConfigured(installHttpsRedirect = false) } fun Application.mymoduleConfigured(installHttpsRedirect: Boolean = true) { if (installHttpsRedirect) { install(HttpsRedirect) } // ... }

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

I get an infinite redirect when using this plugin

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

Last modified: 09 September 2021