Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx replace REMOTE_ADDR with X-Forwarded-For

Tags:

php

nginx

I am quite new to Nginx, and it seems all so confusing. I have my server setup perfectly, but the problem is, since my server is protected using a HTTP proxy; instead of logging the real users IP's, it's logging the proxy server IP.

What I tried doing was setting $_SERVER['REMOTE_ADDR']; to $_SERVER['X-Forwarded-For']; but I'm getting a undefined index error, so I'm guessing I have to define X-Forwarded-For in Nginx? But I am not aware how to do so, I have a simple setup, it's just Nginx with PHP. Nothing more, nothing less.

I've searched all over the web, but can't actually find some information that is friendly to understand.

I have access to the source code, if that somewhat helps. I've tried many solutions, but to no avail.

like image 326
Reverb Avatar asked Sep 19 '14 08:09

Reverb


People also ask

How do I enable X-forwarded-for in nginx?

You can enable ngx_http_realip_module in the Nginx build using the configuration parameter –with-http_realip_module when recompiling Nginx.

Can $_ server Remote_addr be spoofed?

Yes, it's safe. It is the source IP of the TCP connection and can't be substituted by changing an HTTP header.

How do you check X is forwarded for a header?

To check the X-Forwarded-For in action go to Inspect Element -> Network check the request header for X-Forwarded-For like below.


2 Answers

The correct way of doing this is by setting the real_ip_header configuration in nginx.

Example with trusted HTTP proxy IP:

set_real_ip_from 127.0.0.1/32; real_ip_header X-Forwarded-For; 

This way, the $_SERVER['REMOTE_ADDR'] will be correctly filled up in PHP fastcgi.

Documentation link - nginx.org

like image 96
Razvan Grigore Avatar answered Sep 23 '22 14:09

Razvan Grigore


$http_x_forwared_for might contain multiple ip addresses, where the first one should be the client ip. REMOTE_ADDR should only be the client ip.

So by using regex in your nginx.conf, you can set REMOTE_ADDR to the first ip of $http_x_forwarded_for like so:

  set $realip $remote_addr;
  if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
    set $realip $1;
  }
  fastcgi_param REMOTE_ADDR $realip;
like image 43
fredrik Avatar answered Sep 19 '22 14:09

fredrik