proxy.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright © 2014 Red Hat, Inc.
  4. #
  5. # This copyrighted material is made available to anyone wishing to use,
  6. # modify, copy, or redistribute it subject to the terms and conditions
  7. # of the GNU General Public License v.2, or (at your option) any later
  8. # version. This program is distributed in the hope that it will be
  9. # useful, but WITHOUT ANY WARRANTY expressed or implied, including the
  10. # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. # PURPOSE. See the GNU General Public License for more details. You
  12. # should have received a copy of the GNU General Public License along
  13. # with this program; if not, write to the Free Software Foundation,
  14. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  15. #
  16. # Any Red Hat trademarks that are incorporated in the source
  17. # code or documentation are not subject to the GNU General Public
  18. # License and may only be used or replicated with the express permission
  19. # of Red Hat, Inc.
  20. #
  21. """
  22. Makes pagure an application behind a reverse proxy and thus ensure the
  23. redirects are using ``https``.
  24. Source: http://flask.pocoo.org/snippets/35/ by Peter Hansen
  25. """
  26. from __future__ import absolute_import, unicode_literals
  27. class ReverseProxied(object): # pragma: no cover
  28. """Wrap the application in this middleware and configure the
  29. front-end server to add these headers, to let you quietly bind
  30. this to a URL other than / and to an HTTP scheme that is
  31. different than what is used locally.
  32. In nginx:
  33. location /myprefix {
  34. proxy_pass http://192.168.0.1:5001;
  35. proxy_set_header Host $host;
  36. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  37. proxy_set_header X-Scheme $scheme;
  38. proxy_set_header X-Script-Name /myprefix;
  39. }
  40. In apache:
  41. RequestHeader set X-Forwarded-Scheme https early
  42. RequestHeader set X-Scheme https early
  43. RequestHeader add X-Script-Name /myprefix early
  44. RequestHeader set X-Forwarded-Proto https early
  45. :param app: the WSGI application
  46. """
  47. def __init__(self, app):
  48. self.app = app
  49. def __call__(self, environ, start_response):
  50. script_name = environ.get("HTTP_X_SCRIPT_NAME", "")
  51. if script_name:
  52. environ["SCRIPT_NAME"] = script_name
  53. path_info = environ["PATH_INFO"]
  54. if path_info.startswith(script_name):
  55. environ["PATH_INFO"] = path_info[len(script_name) :]
  56. server = environ.get("HTTP_X_FORWARDED_HOST", "")
  57. if server:
  58. environ["HTTP_HOST"] = server
  59. scheme = environ.get("HTTP_X_SCHEME", "")
  60. if scheme:
  61. environ["wsgi.url_scheme"] = scheme
  62. return self.app(environ, start_response)