Skip to content
Server Plugin

HttpsRedirect

必要相依性:io.ktor:ktor-server-http-redirect

程式碼範例: ssl-engine-main-redirect

原生伺服器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。