2017-10-15 62 views
0

我在使用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侧的连接。

+0

你使用任何网络服务器(nginx或apache)为你的应用程序 –

+0

没有网络服务器,只是净/ HTTP包。 – manifest

+0

*“8080只是不会重定向连接”*所以,如果它不做HTTP重定向,那么它会做什么?正常处理请求?时间到?拒绝连接? –

回答

0

您在重定向

http.Redirect失踪port(W,R,请 “https://” + reqhost + r.URL.Path + “:” +端口, http.StatusMovedPermanently )

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

希望它有帮助。

+0

试过这个修复,甚至邮差也无法得到任何回应。不应该在主机之后插入端口,而不是整个路径? – manifest

+0

阅读编辑的问题。该设置使用iptables来映射80> 8080和443> 8081.不需要在重定向中指定任何端口。 –

0

我查了一下是听我的端口,

netstat -tulpn | grep LISTEN 

..和有端口80上要么阿帕奇听其关闭或删除它工作得很好。