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