fix: update default port handling in ProxyHeaderMiddleware for forwarded headers #873
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What I'm changing
Updates the
ProxyHeaderMiddleware._get_forwarded_url_parts()to better respect proxy forwarding headers. This ensures that applications behind reverseproxies/load balancers can correctly determine the original client request URL.
How I did it
Rework the middleware to determine the port using the following priority order:
Port Resolution Rules
The middleware determines the port using the following priority order:
Initial Port Setup
Start with protocol default: 443 for https, 80 for http
If
Hostheader exists:If no
Hostheader:scope["server"]port (server's listening port)Forwarding Header Override
The middleware checks for forwarding headers in priority order:
Standard Forwarded header (highest priority):
host=domain:port→ use explicit porthost=domain(no port) → apply protocol default based on proto valuehost=domain:invalid(malformed port) → apply protocol defaultNon-standard
X-Forwarded-*headers (fallback):X-Forwarded-Portis present and valid → use that portX-Forwarded-HostorX-Forwarded-Protois present without valid port → apply protocoldefault
Examples
Protocol changes trigger port defaults:
Explicit ports are always respected:
Invalid ports use protocol default (not original port):
Server port only used when no forwarding occurs:
Domain changes without port trigger protocol default:
Error Handling
Related Issue(s):
PR Checklist:
pre-commithooks pass locallymake test)make docs)