How to use TLS in Go ReverseProxy?

Viewed 2093

I have sites https://a-b-c.com and https://www.x-y-z.com running behind a reverse proxy on ports 4444 and 5555 respectively.

I had them configured to use letsencrypt tls certificates, but now I get an error when using the reverse proxy and I think I need to use a &tls.config{} that includes their certificates but I don't know how to set it up.

My ReverseProxy looks like:

  director := func(req *http.Request) {                        
    log.Println(req.Host)                                      
    switch req.Host {                                          
    case "a-b-c-.com":                                 
      req.URL.Host = "localhost:4444"                        
      req.URL.Scheme = "https"                                 
    case "x-y-z.com":                                   
      req.URL.Host = "localhost:5555"                           
      req.URL.Scheme = "https"                                                                                   
  }                                                            
  proxy := &httputil.ReverseProxy{Director: director}          
  proxy.Transport = &http.Transport{                           
    Proxy: http.ProxyFromEnvironment,                          
    Dial: (&net.Dialer{                                        
      Timeout:   30 * time.Second,                             
      KeepAlive: 30 * time.Second,                             
    }).Dial,                                                   
    TLSHandshakeTimeout: 10 * time.Second,                     
    TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
  }                                                            

  log.Fatalln(http.ListenAndServe(":443", proxy))              
1 Answers

You don't have to set up your reverse proxy. What you need to do is to set up HTTP server that you attach your reverse proxy to.

Configure TLS listener by passing two pairs of cert/keys:

abcCrt, err := tls.LoadX509KeyPair("a-b-c.crt", "a-b-c.key")
if err != nil {
  panic(err)
}

xyzCrt, err := tls.LoadX509KeyPair("x-y-z.crt", "z-y-z.key")
if err != nil {
  panic(err)
}

tlsConfig := &tls.Config{Certificates: []tls.Certificate{abcCrt, xyzCrt}}
ln, err := tls.Listen("tcp", ":443", tlsConfig) 
if err != nil {
  panic(err)
}

http.Serve(ln, proxy)
Related