Golang ReverseProxy with Apache2 SNI/Hostname error



我正在Go中编写自己的ReverseProxy。ReverseProxy应该连接我的Go Web服务器和我的apache2 Web服务器。但是,当我在另一个IP Adress上运行反向代理时,当反向代理向apache发送请求时,我的apache日志文件中出现了以下错误。

"Hosname xxxx provided via sni and hostname xxxx2 provided via http are different"

我的反向代理和运行在https上的apache网络服务器。

这里有一些代码:

func (p *Proxy) directorApache(req *http.Request) {
    mainServer := fmt.Sprintf("%s:%d", Config.HostMain, Config.PortMain)
    req.URL.Scheme = "https"
    req.URL.Host = mainServer
}
func (p *Proxy) directorGo(req *http.Request) {
    goServer := fmt.Sprintf("%s:%d", Config.GoHost, Config.GoPort)
    req.URL.Scheme = "http"
    req.URL.Host = goServer
}

func (p *Proxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    fmt.Println(req.URL.Path)
    if p.isGoRequest(req) {
        fmt.Println("GO")
        p.goProxy.ServeHTTP(rw, req)
        return
    }
    p.httpProxy.ServeHTTP(rw, req)
}
func main() {
    var configPath = flag.String("conf", "./configReverse.json", "Path to the Json config file.")
    flag.Parse()
    proxy := New(*configPath)
    cert, err := tls.LoadX509KeyPair(Config.PathCert, Config.PathPrivateKey)
    if err != nil {
        log.Fatalf("server: loadkeys: %s", err)
    }
    config := tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{cert}}
    listener, err := net.Listen("tcp",
    net.JoinHostPort(proxy.Host, strconv.Itoa(proxy.Port)))
    if err != nil {
        log.Fatalf("server: listen: %s", err)
    }
    log.Printf("server: listening on %s")
    proxy.listener = tls.NewListener(listener, &config)
    serverHTTPS := &http.Server{
        Handler:   proxy.mux,
        TLSConfig: &config,
    }
    if err := serverHTTPS.Serve(proxy.listener); err != nil {
        log.Fatal("SERVER ERROR:", err)
    }
}

也许有人对这个问题有想法。

简短示例

假设您正在启动对https://your-proxy.local的HTTP请求。您的请求处理程序接受http.Request结构并将其URL字段重写为https://your-apache-backend.local

您没有考虑到的是,原始HTTP请求还包含一个Host头(Host: your-proxy.local)。当将相同的请求传递给http://your-apache-backend.local时,该请求中的Host报头仍然表示Host: your-proxy.local。这就是Apache所抱怨的。

解释

当您使用带有服务器名称指示(SNI)的TLS时,请求主机名不仅用于DNS解析,还用于选择应用于建立TLS连接的SSL证书。另一方面,HTTP 1.1 Host标头用于区分Apache的几个虚拟主机。两个名称必须匹配。Apache HTTPD wiki:中也提到了这个问题

SNI/Request主机名不匹配,或者SNI提供了主机名而请求没有

这是一个浏览器错误。Apache将以400类型的错误拒绝该请求。

解决方案

同时重写Host报头。如果您想保留原始的Host标头,可以将其存储在X-Forwarded-Host标头中(这是一个非标准标头,但在反向代理中广泛使用):

func (p *Proxy) directorApache(req *http.Request) {
    mainServer := fmt.Sprintf("%s:%d", Config.HostMain, Config.PortMain)
    req.URL.Scheme = "https"
    req.URL.Host = mainServer
    req.Header.Set("X-Forwarded-Host", req.Header().Get("Host"))
    req.Host = mainServer
}

最新更新