如何在 Go ReverseProxy 中使用 TLS?

her*_*ain 5 ssl reverse-proxy go

我有站点https://a-b-c.com并分别在端口和https://www.x-y-z.com上的反向代理后面运行。44445555

我将它们配置为使用 LetsEncrypt TLS 证书,但现在使用反向代理时出现错误,我认为我需要使用&tls.config{}包含其证书的证书,但我不知道如何设置它。

我的反向代理看起来像:

  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))              
Run Code Online (Sandbox Code Playgroud)

小智 0

您不必设置反向代理。您需要做的是设置将反向代理附加到的 HTTP 服务器。

通过传递两对证书/密钥来配置 TLS 侦听器:

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)
Run Code Online (Sandbox Code Playgroud)