Ktor 2.0.3 Help

HttpsRedirect

The HttpsRedirect plugin redirects all HTTP requests to the HTTPS counterpart before processing the call. By default, a resource returns 301 Moved Permanently, but it can be configured to be 302 Found.

Add dependencies

To use HttpsRedirect, you need to include the ktor-server-http-redirect artifact in the build script:

implementation("io.ktor:ktor-server-http-redirect:$ktor_version")
implementation "io.ktor:ktor-server-http-redirect:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-http-redirect-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install HttpsRedirect

To install the HttpsRedirect plugin, pass it to the install function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer function call ...

import io.ktor.server.application.* import io.ktor.server.plugins.httpsredirect.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(HttpsRedirect) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.server.application.* import io.ktor.server.plugins.httpsredirect.* // ... fun Application.module() { install(HttpsRedirect) // ... }

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

Configure HttpsRedirect

The code snippet below shows how to configure the desired HTTPS port and return 301 Moved Permanently for the requested resource:

install(HttpsRedirect) { sslPort = 8443 permanentRedirect = true }

You can find the full example here: ssl-engine-main-redirect.

Last modified: 28 June 2022