amazon-web-services - Golang 在 AWS 中重定向到 HTTPS

标签 amazon-web-services redirect go https

我在 Golang 服务上的 EC2 实例中将 HTTP 流量重定向到 HTTPS 时遇到问题。直接转到 https://sub.domain.com 时连接工作正常,但来自 HTTP 的重定向似乎不起作用。

没有负载均衡器,它只使用 net/http 包作为网络服务器。

我还在使用应该将 HTTP/HTTPS 请求分别重定向到端口 8080/8081 的 iptables。

为了缩小可能性,应用于实例的安全组允许从任何 IPv4 或 IPv6 地址连接到端口 80 和 443。

这是服务于 HTTPS 的服务器代码,应该重定向 HTTP 请求;

    // LetsEncrypt setup
    certManager := autocert.Manager{
            Prompt:     autocert.AcceptTOS,
            HostPolicy: autocert.HostWhitelist("sub.domain.com"), // your domain here
            Cache:      autocert.DirCache("certs"),          // folder for storing certificates
    }
    server := &http.Server{
            Addr:      ":8081",
            Handler:   context.ClearHandler(http.DefaultServeMux),
            TLSConfig: &tls.Config{GetCertificate: certManager.GetCertificate},
    }
    // open https server
    err = server.ListenAndServeTLS("", "")
    if err != nil {
            fmt.Printf("ListenAndServe: %s\n", err)
    }
    // redirect everything to https
    go http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            reqhost := strings.Split(r.Host, ":")[0]
            http.Redirect(w, r, "https://" + reqhost + r.URL.Path, http.StatusMovedPermanently)
    }))

这是我从 iptables 得到的 PREROUTING 规则,其他链是空的;

    Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    7   420 REDIRECT   tcp  --  eth0   any     anywhere             anywhere             tcp dpt:https redir ports 8081
   45  2508 REDIRECT   tcp  --  eth0   any     anywhere             anywhere             tcp dpt:http redir ports 8080

两个重定向都根据请求获取数据包,但 8080 不会将连接重定向到 HTTPS 端。

最佳答案

您在重定向中缺少端口

http.Redirect(w, r, "https://" + reqhost + r.URL.Path + ":" + port, http.StatusMovedPermanently)

您需要在其中添加端口。 您也可以在请求中使用 postman 来查看发送的位置 URL 是什么。

希望对您有所帮助。

关于amazon-web-services - Golang 在 AWS 中重定向到 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757870/

相关文章:

amazon-web-services - aws 描述显示空列表的实例

django - 结合使用AWS Elastic Search和VPC端点django haystack

redirect - 仅重定向页面的 Google Analytics(分析)速度如此之高

apache - http 到 https 重定向不起作用(Letsencrypt)

go - 获取结构名称而不获取包名称或指针

amazon-web-services - 亚马逊 Lex 错误 : An error occurred (BadRequestException) when calling the PutIntent operation: RelativeId does not match Lex ARN format

amazon-web-services - 如何解决 AWS S3 中的 'HttpVersionNotSupported' 错误?

linux - 运行一个在后台等待输入的进程,不暂停也不发送输入

go - 为什么 Atom 编辑器不能自动完成本地包的工作?

go - 如何在 Go 中创建可嵌入的 C-API 库?