Ben
Ben

Reputation: 16650

Access HTTP_X_FORWARDED_FOR Header in Apache for Django

I want to read client's IP address in Django. When I try to do so now with the HTTP_X_FORWARDED_FOR Header, it fails. The key is not present.

Apparently this is related to configuring my Apache server (I'm deploying with apache and mod_wsgi). I have to configure it as a reverse proxy? How do I do that, are there security implications?

Thanks, Brendan

Upvotes: 2

Views: 5431

Answers (2)

Max
Max

Reputation: 7119

Usually these headers are available in request.META. So you might try request.META['HTTP_X_FORWARDED_FOR'].

Are you using Apache as a reverse proxy as well? This doesn't seem right to me. Usually one uses a lighter weight static server like nginx as the reverse proxy to Apache running the app server. Nginx can send any headers you like using the proxy_set_header config entry.

Upvotes: 1

jphoude
jphoude

Reputation: 373

I'm not familiar with mod_wsgi, but usually the client IP address is available in the REMOTE_ADDR environment variable. If the client is accessing the website through a proxy, or if your setup includes a reverse proxy, the proxy address will be in the REMOTE_ADDR variable instead, and the proxy may copy the original client IP in HTTP_X_FORWARDED_FOR (depending on it's configuration).

If you have a request object, you can access these environment variables like this :

request.environ.get('REMOTE_ADDR')
request.environ.get('HTTP_X_FORWARDED_FOR')

There should be no need to change your Apache configuration or configure a reverse proxy just to get the client's IP address.

Upvotes: 0

Related Questions