nginx varnish nginx php-fpm: real ip for php's _SERVER['REMOTE_ADDR']

7,870

This is a specific answer. ;)

You could add a x-forwarded-for in N1, let that pass through varnish and N2 to fastcgi:

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Then in fastcgi params:

fastcgi_param REMOTE_ADDR $http_x_forwarded_for;
Share:
7,870

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin almost 2 years

    This is specific question.

    A Nginx server (call it N1) listens on :80 and forwards to varnish with proxy_pass Varnish listens on 127.0.0.1:6081 and forwards to Nginx (N2) on 8080. N2 talks to the php-fpm socket.

    N1<>V<>N2<>P

    N1:

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
    
        proxy_pass http://varnish/;
        proxy_redirect off;
    }
    

    currently

    $_SERVER['REMOTE_ADDR'] == '127.0.0.1'

    desired

    $_SERVER['REMOTE_ADDR'] == 'The real remote addr'

  • SiXoS
    SiXoS over 10 years
    There's a common trick with a module called "RealIpHeader" or something, and it also allows rewriting of the REMOTE_ADDR, but I figure it's more clean using the x-forwarded-for.
  • Admin
    Admin over 10 years
    however $http_x_forwarded_for is an array. I'm not sure of the type of $_SERVER['REMOTE_ADDR']. So when passing through 2 proxies, like in this case there will be 2 IPs in $_SERVER['X-FORWARDED-FOR']. Your answer helped me because my final solution was fastcgi_param REMOTE_ADDR $http_x_real_ip; since I set X-Real-IP in N1.
  • Konstantin Pereiaslov
    Konstantin Pereiaslov over 7 years
    Don't do this. as @dalu mentioned, X-Forwarded-For might have comma-separated IPs, and this will lead to incorrect headers. The right way to do it using real_ip nginx module: nginx.org/en/docs/http/ngx_http_realip_module.html