Getting the client IP address behind a proxy in Apache

By Nuno Mariz, on 20 May 2009 @ 09:45

Typically in my Django projects deployments I use Nginx as a front-end web server to handle static content while proxying all other requests to Apache.

When the request arrives to Apache, the client IP address is 127.0.0.1. We need to configure Apache to accept the IP address from X-Real-IP or X-Forwarded-For headers set by Nginx.

To solve this problem I use mod_rpaf that does exactly the opposite of mod_proxy_add_forward.

In my Nginx virtualhost configuration I have something like:

server {
    ...
    location  / {
        proxy_pass        http://127.0.0.1:8080;
        proxy_set_header  Host             $http_host;
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        ...
    }
    ...
}

This also applies if your are using a different webserver as front-end such as Lighttpd or another instance of Apache.

Comments

  • #1 By ??? on 21 May 2009 @ 03:50
    Any idea about lighttpd with apache?
  • #2 By Jökull on 21 May 2009 @ 09:58
    There's middleware in Django that handles this

    django.middleware.http.SetRemoteAddrFromForwardedFor
  • #3 By Nuno Mariz on 21 May 2009 @ 10:10
    If you are using Lighttpd as the front-end web server you should use mod_proxy: http://redmine.lighttpd.net/projects/...

    Have you tried mod_rpaf on your apache?
  • #4 By Nuno Mariz on 21 May 2009 @ 10:20
    @Jökull Yes, but I need mod_rpaf in Apache for the logs.
    If you are not using logs in Apache, SetRemoteAddrFromForwardedFor is the solution, thanks for the tip.
    The Django documentation for this: http://docs.djangoproject.com/en/dev/...
  • #5 By web hosting on 23 December 2009 @ 11:07
    Another important note to this

    the HTTP_X_FORWARDED_FOR may contain an array of IP, this can happen if you connect through a proxy.
    What also happens when this happens is that the REMOTE_ADDR may contain the proxy IP.

    to avoid this problem you can parse the HTTP_X_FORWARDED_FOR for the last entery IP.
  • #6 By Pedro Assuncao on 14 February 2010 @ 22:46
    Thanks for the tip :)
Comments are closed.