Ktor 2.0.3 Help

Forwarded headers

The ForwardedHeaders and XForwardedHeaders plugins allow you to handle reverse proxy headers to get information about the original request when a Ktor server is placed behind a reverse proxy. This might be useful for logging purposes.

  • ForwardedHeaders handles the Forwarded header (RFC 7239)

  • XForwardedHeaders handles the following X-Forwarded- headers:

    • X-Forwarded-Host/X-Forwarded-Server

    • X-Forwarded-For

    • X-Forwarded-By

    • X-Forwarded-Proto/X-Forwarded-Protocol

    • X-Forwarded-SSL/Front-End-Https

Add dependencies

To use the ForwardedHeaders/XForwardedHeaders plugins, you need to include the ktor-server-forwarded-header artifact in the build script:

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

Install plugins

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

... or a specified module.

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

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

... or a specified module.

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

ForwardedHeaders and XForwardedHeaders don't require any special configuration.

Get request information

Proxy request information

To get information about the proxy request, use the call.request.local property inside the route handler. The code snippet below shows how to obtain information about the host and port:

get("/hello") { val localHost = call.request.local.remoteHost val localPort = call.request.local.port }

Original request information

To read information about the original request, use the call.request.origin property:

get("/hello") { val remoteHost = call.request.origin.remoteHost val remotePort = call.request.origin.port }

You can find the full example here: forwarded-header.

Last modified: 28 June 2022