/circuits/web/dispatchers/virtualhosts.py

https://bitbucket.org/prologic/circuits/ · Python · 59 lines · 28 code · 11 blank · 20 comment · 3 complexity · 73bf2d7e5841f131ec9106920bbe92a6 MD5 · raw file

  1. # Module: virtualhost
  2. # Date: 13th September 2007
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. """VirtualHost
  5. This module implements a virtual host dispatcher that sends requests
  6. for configured virtual hosts to different dispatchers.
  7. """
  8. try:
  9. from urllib.parse import urljoin
  10. except ImportError:
  11. from urlparse import urljoin # NOQA
  12. from circuits import handler, BaseComponent
  13. class VirtualHosts(BaseComponent):
  14. """Forward to anotehr Dispatcher based on the Host header.
  15. This can be useful when running multiple sites within one server.
  16. It allows several domains to point to different parts of a single
  17. website structure. For example:
  18. - http://www.domain.example -> /
  19. - http://www.domain2.example -> /domain2
  20. - http://www.domain2.example:443 -> /secure
  21. :param domains: a dict of {host header value: virtual prefix} pairs.
  22. :type domains: dict
  23. The incoming "Host" request header is looked up in this dict,
  24. and, if a match is found, the corresponding "virtual prefix"
  25. value will be prepended to the URL path before passing the
  26. request onto the next dispatcher.
  27. Note that you often need separate entries for "example.com"
  28. and "www.example.com". In addition, "Host" headers may contain
  29. the port number.
  30. """
  31. channel = "web"
  32. def __init__(self, domains):
  33. super(VirtualHosts, self).__init__()
  34. self.domains = domains
  35. @handler("request", priority=1.0)
  36. def _on_request(self, event, request, response):
  37. path = request.path.strip("/")
  38. header = request.headers.get
  39. domain = header("X-Forwarded-Host", header("Host", ""))
  40. prefix = self.domains.get(domain, "")
  41. if prefix:
  42. path = urljoin("/%s/" % prefix, path)
  43. request.path = path