Skip to content

Commit

Permalink
Add "X-Forwarded-Proto: https" header
Browse files Browse the repository at this point in the history
Some backends may depend on this to properly assemble urls.
  • Loading branch information
Artyom Pervukhin committed Mar 17, 2017
1 parent 87e86d0 commit 79c3171
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion leproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func setProxy(mapping map[string]string) (http.Handler, error) {
if u, err := url.Parse(backendAddr); err == nil {
switch u.Scheme {
case "http", "https":
rp := httputil.NewSingleHostReverseProxy(u)
rp := newSingleHostReverseProxy(u)
rp.ErrorLog = log.New(ioutil.Discard, "", 0)
rp.BufferPool = bufPool{}
mux.Handle(hostname+"/", rp)
Expand All @@ -121,6 +121,7 @@ func setProxy(mapping map[string]string) (http.Handler, error) {
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = req.Host
req.Header.Set("X-Forwarded-Proto", "https")
},
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
Expand Down Expand Up @@ -180,3 +181,36 @@ var bufferPool = &sync.Pool{
return make([]byte, 32*1024)
},
}

// newSingleHostReverseProxy is a copy of httputil.NewSingleHostReverseProxy
// with addition of "X-Forwarded-Proto" header.
func newSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
targetQuery := target.RawQuery
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
req.Header.Set("User-Agent", "")
}
req.Header.Set("X-Forwarded-Proto", "https")
}
return &httputil.ReverseProxy{Director: director}
}

func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}

0 comments on commit 79c3171

Please sign in to comment.