utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package dpcore
  2. import (
  3. "net/url"
  4. "strings"
  5. )
  6. // replaceLocationHost rewrite the backend server's location header to a new URL based on the given proxy rules
  7. // If you have issues with tailing slash, you can try to fix them here (and remember to PR :D )
  8. func replaceLocationHost(urlString string, rrr *ResponseRewriteRuleSet, useTLS bool) (string, error) {
  9. u, err := url.Parse(urlString)
  10. if err != nil {
  11. return "", err
  12. }
  13. //Update the schemetic if the proxying target is http
  14. //but exposed as https to the internet via Zoraxy
  15. if useTLS {
  16. u.Scheme = "https"
  17. } else {
  18. u.Scheme = "http"
  19. }
  20. u.Host = rrr.OriginalHost
  21. if strings.Contains(rrr.ProxyDomain, "/") {
  22. //The proxy domain itself seems contain subpath.
  23. //Trim it off from Location header to prevent URL segment duplicate
  24. //E.g. Proxy config: blog.example.com -> example.com/blog
  25. //Location Header: /blog/post?id=1
  26. //Expected Location Header send to client:
  27. // blog.example.com/post?id=1 instead of blog.example.com/blog/post?id=1
  28. ProxyDomainURL := "http://" + rrr.ProxyDomain
  29. if rrr.UseTLS {
  30. ProxyDomainURL = "https://" + rrr.ProxyDomain
  31. }
  32. ru, err := url.Parse(ProxyDomainURL)
  33. if err == nil {
  34. //Trim off the subpath
  35. u.Path = strings.TrimPrefix(u.Path, ru.Path)
  36. }
  37. }
  38. return u.String(), nil
  39. }
  40. // Debug functions
  41. func ReplaceLocationHost(urlString string, rrr *ResponseRewriteRuleSet, useTLS bool) (string, error) {
  42. return replaceLocationHost(urlString, rrr, useTLS)
  43. }