swiftperfect

Redirect all HTTP to HTTPS without ELB


I'm trying to redirect all my APIs and web HTTP requests to HTTPS in Swift Perfect. I have deployed code into AWS. When I Googled, all I'm getting is using ELB which I'm not using. Are there any workaround to redirect to https port inside code?


Solution

  • After lot of research and people guidance I figured out a solution. Posting it so that other don't have to spend time on this on Perfect

    For redirect all HTTP to HTTPS here is the solution

    let mainDomain = "www.<your domain>.com(or anything)"
    
    var nonSecureRoutes = Routes()
    nonSecureRoutes.add(method: .get, uri: "/**", handler: {
        request, response in
        response.setHeader(.location, value: "https://\(request.header(.host) ?? mainDomain)\(request.uri)")
            .completed(status: .movedPermanently)
    })
    
    let certPath = "/cert/path.pem"
    let keyPath = "key/path.pem"
    
    var certVerifyMode = OpenSSLVerifyMode()
    certVerifyMode = .sslVerifyPeer
    
    do {
        try HTTPServer.launch(
            .server(name: mainDomain, port: 80, routes: nonSecureRoutes),
            .secureServer(TLSConfiguration(certPath: certPath, keyPath: keyPath, certVerifyMode: certVerifyMode), name: mainDomain, port: 443, routes: routes))
    
    } catch PerfectError.networkError(let err, let msg) {
        print("Network error thrown: \(err) \(msg)")
    }