Skip to content
Server Plugin

HttpsRedirect

所需依赖项:io.ktor:ktor-server-http-redirect

代码示例: ssl-engine-main-redirect

Native 服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持:✅

HttpsRedirect 插件会在处理调用之前,将所有 HTTP 请求重定向到对应的 HTTPS。默认情况下,资源会返回 301 Moved Permanently,但也可以配置为返回 302 Found。

添加依赖项 ​

要使用 HttpsRedirect,请将 ktor-server-http-redirect 工件添加到您的构建脚本中:

kotlin
implementation(ktorLibs.server.httpRedirect)
上面的代码段使用 Ktor 版本目录 (version catalog) 来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.httpRedirect
上面的代码段使用 Ktor 版本目录 (version catalog) 来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-http-redirect-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安装 HttpsRedirect ​

要将 HttpsRedirect 插件安装到您的应用程序中,请在指定的 模块模块允许您通过对路由进行分组来构建应用程序结构。中将其传递给 install 函数。以下示例展示了如何安装 HttpsRedirect:

  • 在 embeddedServer() 函数调用中。
  • 在 Application 类上显式定义的 module() 扩展函数中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.httpsredirect.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(HttpsRedirect)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.plugins.httpsredirect.*
// ...
fun Application.module() {
    install(HttpsRedirect)
    // ...
}

上述代码使用默认配置安装了 HttpsRedirect 插件。

当处于反向代理之后时,您需要安装 ForwardedHeader 或 XForwardedHeader 插件以正确检测 HTTPS 请求。如果在安装这些插件之一后出现无限重定向,请查看此常见问题解答条目了解更多详情。

配置 HttpsRedirect ​

下面的代码段展示了如何配置所需的 HTTPS 端口,并针对所请求的资源返回 301 Moved Permanently:

kotlin
install(HttpsRedirect) {
    sslPort = 8443
    permanentRedirect = true
}

您可以在此处找到完整示例:ssl-engine-main-redirect。