flaskfix.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. from urllib.parse import urlparse
  4. from werkzeug.middleware.proxy_fix import ProxyFix
  5. from werkzeug.serving import WSGIRequestHandler
  6. from searx import settings
  7. class ReverseProxyPathFix:
  8. '''Wrap the application in this middleware and configure the
  9. front-end server to add these headers, to let you quietly bind
  10. this to a URL other than / and to an HTTP scheme that is
  11. different than what is used locally.
  12. http://flask.pocoo.org/snippets/35/
  13. In nginx:
  14. location /myprefix {
  15. proxy_pass http://127.0.0.1:8000;
  16. proxy_set_header Host $host;
  17. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  18. proxy_set_header X-Scheme $scheme;
  19. proxy_set_header X-Script-Name /myprefix;
  20. }
  21. :param wsgi_app: the WSGI application
  22. '''
  23. # pylint: disable=too-few-public-methods
  24. def __init__(self, wsgi_app):
  25. self.wsgi_app = wsgi_app
  26. self.script_name = None
  27. self.scheme = None
  28. self.server = None
  29. if settings['server']['base_url']:
  30. # If base_url is specified, then these values from are given
  31. # preference over any Flask's generics.
  32. base_url = urlparse(settings['server']['base_url'])
  33. self.script_name = base_url.path
  34. if self.script_name.endswith('/'):
  35. # remove trailing slash to avoid infinite redirect on the index
  36. # see https://github.com/searx/searx/issues/2729
  37. self.script_name = self.script_name[:-1]
  38. self.scheme = base_url.scheme
  39. self.server = base_url.netloc
  40. def __call__(self, environ, start_response):
  41. script_name = self.script_name or environ.get('HTTP_X_SCRIPT_NAME', '')
  42. if script_name:
  43. environ['SCRIPT_NAME'] = script_name
  44. path_info = environ['PATH_INFO']
  45. if path_info.startswith(script_name):
  46. environ['PATH_INFO'] = path_info[len(script_name) :]
  47. scheme = self.scheme or environ.get('HTTP_X_SCHEME', '')
  48. if scheme:
  49. environ['wsgi.url_scheme'] = scheme
  50. server = self.server or environ.get('HTTP_X_FORWARDED_HOST', '')
  51. if server:
  52. environ['HTTP_HOST'] = server
  53. return self.wsgi_app(environ, start_response)
  54. def patch_application(app):
  55. # serve pages with HTTP/1.1
  56. WSGIRequestHandler.protocol_version = "HTTP/{}".format(settings['server']['http_protocol_version'])
  57. # patch app to handle non root url-s behind proxy & wsgi
  58. app.wsgi_app = ReverseProxyPathFix(ProxyFix(app.wsgi_app))