27 lines
944 B
Python
27 lines
944 B
Python
"""
|
|
ScriptNameFix WSGI middleware.
|
|
|
|
When nginx strips the path prefix before forwarding to a Flask app it also
|
|
sets the X-Script-Name header (e.g. /digiserver). This middleware reads
|
|
that header and sets SCRIPT_NAME in the WSGI environ so that Flask's
|
|
url_for() generates absolute URLs with the correct prefix.
|
|
|
|
Usage in the app factory:
|
|
from app.utils.script_name_fix import ScriptNameFix
|
|
app.wsgi_app = ScriptNameFix(app.wsgi_app)
|
|
"""
|
|
|
|
|
|
class ScriptNameFix:
|
|
def __init__(self, app):
|
|
self.app = app
|
|
|
|
def __call__(self, environ, start_response):
|
|
script_name = environ.get('HTTP_X_SCRIPT_NAME', '').rstrip('/')
|
|
if script_name:
|
|
environ['SCRIPT_NAME'] = script_name
|
|
path_info = environ.get('PATH_INFO', '/')
|
|
if path_info.startswith(script_name):
|
|
environ['PATH_INFO'] = path_info[len(script_name):] or '/'
|
|
return self.app(environ, start_response)
|