Matt Robenolt

Stalk me:

Handle X-Forwarded-Port Header in Django

When running on a non-standard port, and behind a load balancer/proxy, it has become “standard”[1] to forward along a header called X-Forwarded-Port.

This header is very similar to X-Forwarded-Host, X-Forwarded-Proto, and X-Forwarded-For in the sense that it’s forwarding relevent information about the originating request and telling your backend to ignore the values it’s aware of.

In this case, X-Forwarded-Port is not supported by Django natively, and the easiest way to handle it is through a simple middleware:

class XForwardedPort(object):
    def process_request(self, request):
            request.META['SERVER_PORT'] = request.META['HTTP_X_FORWARDED_PORT']
        except KeyError:
        return None

This will allow urls to be properly reversed with the correct port as you’d expect.