HttpsRedirect
note
This help topic is in development and will be updated in the future.
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.
Usage
1. fun Application.main() {
2. install(HttpsRedirect)
3. // install(XForwardedHeaderSupport) // Required when behind a reverse-proxy
4. }
The code above installs the HttpsRedirect feature with the default configuration.
note
When behind a reverse-proxy, you will need to install the
ForwardedHeaderSupportor theXForwardedHeaderSupportfeature, for theHttpsRedirectfeature to properly detect HTTPS requests.
Configuration
1. fun Application.main() {
2. install(HttpsRedirect) {
3. // The port to redirect to. By default 443, the default HTTPS port.
4. sslPort = 443
5. // 301 Moved Permanently, or 302 Found redirect.
6. permanentRedirect = true
7. }
8. }
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.
1. @Test
2. fun testRedirectHttps() {
3. withTestApplication {
4. application.install(XForwardedHeaderSupport)
5. application.install(HttpsRedirect)
6. application.routing {
7. get("/") {
8. call.respond("ok")
9. }
10. }
12. handleRequest(HttpMethod.Get, "/", {
13. addHeader(HttpHeaders.XForwardedProto, "https")
14. }).let { call ->
15. assertEquals(HttpStatusCode.OK, call.response.status())
16. }
17. }
18. }
Do not install the feature when testing or uninstall it
Uninstalling it:
1. application.uninstall(HttpsRedirect)
Prevent installation in the first place:
1. // The function referenced in the application.conf
2. fun Application.mymodule() {
3. mymoduleConfigured()
4. }
6. // The function referenced in the tests
7. fun Application.mymoduleForTesting() {
8. mymoduleConfigured(installHttpsRedirect = false)
9. }
11. fun Application.mymoduleConfigured(installHttpsRedirect: Boolean = true) {
12. if (installHttpsRedirect) {
13. install(HttpsRedirect)
14. }
15. // ...
16. }
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.

