在Golang服务上的EC2实例中,我在将HTTP流量重定向到HTTPS时遇到了问题。当直接连接到https://sub.domain.com时,连接工作得很好,但从HTTP重定向似乎不起作用。
没有负载均衡器,它只使用net/http包作为web服务器。
我还使用了iptables,它们应该将HTTP/HTTPS请求分别重定向到端口8080/8081。
为了缩小可能性,应用到实例的安全组具有从任何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中的预处理规则,其他的链都是空的;
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端。
发布于 2017-10-16 02:55:07
您在重定向中缺少port
端口(w,r,"https://“+ reqhost +
+ ":”+http.Redirect,r.URL.Path )
您需要在其中添加端口。您还可以在请求中使用postman来查看发送的位置URL。
希望能有所帮助。
发布于 2017-10-16 05:43:09
我检查了在我的端口上监听的是什么
netstat -tulpn | grep LISTEN..and有apache在监听端口80。无论是关闭它还是删除它都可以正常工作。
https://stackoverflow.com/questions/46757870
复制相似问题