Ktor 2.1.1 Help


The HSTS plugin adds the required HTTP Strict Transport Security headers to the request according to the RFC 6797. When the browser receives HSTS policy headers, it no longer attempts to connect to the server with insecure connections for a given period.

Add dependencies

To use HSTS, you need to include the ktor-server-hsts artifact in the build script:

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

Install HSTS

To install the HSTS 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.hsts.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(HSTS) // ... }.start(wait = true) }

... or a specified module.

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

The code above installs HSTS with the default configuration.

Configure HSTS

HSTS exposes its settings via HSTSConfig. The example below shows how to use the maxAgeInSeconds property to specify how long the client should keep the host in a list of known HSTS hosts:

install(HSTS) { maxAgeInSeconds = 10 }

You can also provide different HSTS configurations for different hosts using withHost:

install(HSTS) { maxAgeInSeconds = 10 withHost("sample-host") { maxAgeInSeconds = 60 includeSubDomains = false } }

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

Last modified: 21 September 2022