middlewares.py 661 B

1234567891011121314
  1. from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
  2. from starlette.requests import Request
  3. from starlette.responses import Response
  4. class RedirectWithPrefixMiddleware(BaseHTTPMiddleware):
  5. async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
  6. prefix = request.headers.get('X-Forwarded-Prefix', '')
  7. response = await call_next(request)
  8. if 'Location' in response.headers and response.headers['Location'].startswith('/'):
  9. new_location = prefix + response.headers['Location']
  10. response.headers['Location'] = new_location
  11. return response