From 2fb26a232c7ddca5eaa4de3a510a4c0354384b4b Mon Sep 17 00:00:00 2001 From: han0 Date: Wed, 22 Feb 2023 15:57:02 +0800 Subject: [PATCH] feat: ReverseProxied --- nc_http/tools/constant/__init__.py | 3 ++ .../constant/{base.py => constant_dict.py} | 0 nc_http/tools/reverse_proxied.py | 33 +++++++++++++++++++ 3 files changed, 36 insertions(+) rename nc_http/tools/constant/{base.py => constant_dict.py} (100%) create mode 100644 nc_http/tools/reverse_proxied.py diff --git a/nc_http/tools/constant/__init__.py b/nc_http/tools/constant/__init__.py index e69de29..2590301 100644 --- a/nc_http/tools/constant/__init__.py +++ b/nc_http/tools/constant/__init__.py @@ -0,0 +1,3 @@ +""" +常量相关 +""" diff --git a/nc_http/tools/constant/base.py b/nc_http/tools/constant/constant_dict.py similarity index 100% rename from nc_http/tools/constant/base.py rename to nc_http/tools/constant/constant_dict.py diff --git a/nc_http/tools/reverse_proxied.py b/nc_http/tools/reverse_proxied.py new file mode 100644 index 0000000..382b83d --- /dev/null +++ b/nc_http/tools/reverse_proxied.py @@ -0,0 +1,33 @@ +class ReverseProxied: + """Wrap the application in this middleware and configure the + front-end server to add these headers, to let you quietly bind + this to a URL other than / and to an HTTP scheme that is + different than what is used locally. + + In nginx: + location /myprefix { + proxy_pass http://192.168.0.1:5001; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Scheme $scheme; + proxy_set_header X-Script-Name /myprefix; + } + + :param app: the WSGI application + """ + + def __init__(self, app): + self.app = app + + def __call__(self, environ, start_response): + script_name = environ.get('HTTP_X_SCRIPT_NAME', '') + if script_name: + environ['SCRIPT_NAME'] = script_name + path_info = environ['PATH_INFO'] + if path_info.startswith(script_name): + environ['PATH_INFO'] = path_info[len(script_name):] + + scheme = environ.get('HTTP_X_SCHEME', '') + if scheme: + environ['wsgi.url_scheme'] = scheme + return self.app(environ, start_response)