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