1
0

utils.go 2.1 KB

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