1 | # This file contains middleware to update request.META when running behind
|
---|
2 | # multiple reverse proxis. Django cannot cope with this, and fails to generate
|
---|
3 | # the correct URIs, particularly the host name.
|
---|
4 |
|
---|
5 | class MultipleProxyMiddleware(object):
|
---|
6 |
|
---|
7 | FORWARDED_FOR_FIELDS = [
|
---|
8 | 'HTTP_X_FORWARDED_FOR',
|
---|
9 | 'HTTP_X_FORWARDED_HOST',
|
---|
10 | 'HTTP_X_FORWARDED_SERVER',
|
---|
11 | ]
|
---|
12 |
|
---|
13 | def process_request(self, request):
|
---|
14 | """
|
---|
15 | When a reverse proxy forwards on a request to a backend server, the proxy
|
---|
16 | adds/rewrites some of the headers so that the next server knows it was proxied.
|
---|
17 | Eg, after going through proxy1:
|
---|
18 | X-Forwarded-Host: proxy1
|
---|
19 | If it then goes through an additional proxy, the fields are updated, to be a
|
---|
20 | list of the proxies it has travelled through.
|
---|
21 | Eg, after then going through proxy2:
|
---|
22 | X-Forwarded-Host: proxy1, proxy2
|
---|
23 | Django cannot handle this, so this middleware rewrites these proxy headers
|
---|
24 | so that only the most recent proxy is mentioned.
|
---|
25 | """
|
---|
26 | for field in self.FORWARDED_FOR_FIELDS:
|
---|
27 | if field in request.META:
|
---|
28 | if ',' in request.META[field]:
|
---|
29 | parts = request.META[field].split(',')
|
---|
30 | request.META[field] = parts[-1].strip()
|
---|
31 |
|
---|