【发布时间】: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