【问题标题】:Golang redirecting to HTTPS in AWSGolang 重定向到 AWS 中的 HTTPS
【发布时间】:2018-03-27 05:45:45
【问题描述】:

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

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

我也在使用应该将 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 端。

【问题讨论】:

  • 您是否为您的应用程序使用任何 Web 服务器(nginx 或 apache)
  • 没有网络服务器,只有 net/http 包。
  • "8080 just won't redirect the connection" 那么,如果它不做 HTTP 重定向,那么它做什么呢?正常处理请求?暂停?连接被拒绝?
  • 使用 curl 进行正常的 HTTP 连接表示连接被拒绝,是的。

标签: amazon-web-services redirect go https


【解决方案1】:

我用

检查了我的端口上正在监听的内容
netstat -tulpn | grep LISTEN

..并且有 apache 在端口 80 上侦听。关闭或删除它都可以正常工作。

【讨论】:

    【解决方案2】:

    您在重定向中缺少port

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

    您需要在其中添加端口。 您也可以在请求中使用邮递员来查看发送的位置 URL。

    希望对你有帮助。

    【讨论】:

    • 试过这个修复,即使是邮递员也无法得到任何回应。端口不应该插在主机之后,而不是整个路径吗?
    • 阅读编辑后的问题。该设置使用 iptables 映射 80 > 8080 和 443 > 8081。无需在重定向中指定任何端口。
    猜你喜欢
    • 2018-10-08
    • 1970-01-01
    • 2020-12-21
    • 2017-09-30
    • 2018-03-07
    • 2018-09-23
    • 2019-12-13
    • 2018-04-15
    • 2011-08-18
    相关资源
    最近更新 更多