2017-10-15 57 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上要麼阿帕奇聽其關閉或刪除它工作得很好。