utils.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. //Issue #39: Check if it is location target match the proxying domain
  21. //E.g. Proxy config: blog.example.com -> example.com/blog
  22. //Check if it is actually redirecting to example.com instead of a new domain
  23. //like news.example.com.
  24. // The later check bypass apache screw up method of redirection header
  25. // e.g. https://imuslab.com -> http://imuslab.com:443
  26. if rrr.ProxyDomain != u.Host && !strings.Contains(u.Host, rrr.OriginalHost+":") {
  27. //New location domain not matching proxy target domain.
  28. //Do not modify location header
  29. return urlString, nil
  30. }
  31. u.Host = rrr.OriginalHost
  32. if strings.Contains(rrr.ProxyDomain, "/") {
  33. //The proxy domain itself seems contain subpath.
  34. //Trim it off from Location header to prevent URL segment duplicate
  35. //E.g. Proxy config: blog.example.com -> example.com/blog
  36. //Location Header: /blog/post?id=1
  37. //Expected Location Header send to client:
  38. // blog.example.com/post?id=1 instead of blog.example.com/blog/post?id=1
  39. ProxyDomainURL := "http://" + rrr.ProxyDomain
  40. if rrr.UseTLS {
  41. ProxyDomainURL = "https://" + rrr.ProxyDomain
  42. }
  43. ru, err := url.Parse(ProxyDomainURL)
  44. if err == nil {
  45. //Trim off the subpath
  46. u.Path = strings.TrimPrefix(u.Path, ru.Path)
  47. }
  48. }
  49. return u.String(), nil
  50. }
  51. // Debug functions
  52. func ReplaceLocationHost(urlString string, rrr *ResponseRewriteRuleSet, useTLS bool) (string, error) {
  53. return replaceLocationHost(urlString, rrr, useTLS)
  54. }