我在使用Golang服務在EC2實例中將HTTP流量重定向到HTTPS時出現問題。直接連接到https://sub.domain.com時,連接正常工作,但來自HTTP的重定向似乎不起作用。Golang重定向到AWS中的HTTPS
沒有負載均衡器和它的使用只淨/ 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的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側的連接。
你使用任何網絡服務器(nginx或apache)爲你的應用程序 –
沒有網絡服務器,只是淨/ HTTP包。 – manifest
*「8080只是不會重定向連接」*所以,如果它不做HTTP重定向,那麼它會做什麼?正常處理請求?時間到?拒絕連接? –