flaskfix.py 2.6 KB

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