Redirect HTTP requests to HTTPS

预计阅读时间: 4 分钟

This 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.

本特性在 io.ktor.features.HttpsRedirect 类中定义,无需任何额外构件。

Usage

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

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

When behind a reverse-proxy, you will need to install the ForwardedHeaderSupport or the XForwardedHeaderSupport feature, for the HttpsRedirect feature to properly detect HTTPS requests.

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
    }
}

Testing

Applying this feature changes how testing works. After applying this feature, 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 feature 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 feature when testing or uninstall it

Uninstalling it:

application.uninstall(HttpsRedirect)

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 feature is installed and other things that you are not doing in tests.

I get an infinite redirect when using this feature

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