我在 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/