Ktor 3.0.0 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 to the application, pass it to the install function in the specified module. The code snippets below show how to install HttpsRedirect...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

import io.ktor.server.application.* import io.ktor.server.plugins.httpsredirect.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(HttpsRedirect) // ... }.start(wait = true) }
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: 21 September 2022