User Tools

Site Tools


x-forwarded-for_centos_nginx

Nginx – CentOS

First you will need to find out the private ip address of your loadbalancer. The easiest way to do this is tail your logs for your domain with

tail -f -n 5 /var/log/httpd/website-access.log

You should then be presented with a private net ip, in my case it is 10.189.255.252

You will then need to edit /etc/nginx/nginx.conf and enter the following lines into your config file (in the http { section) with your load balancers internal ip address in place of mine.

set_real_ip_from 10.189.255.252;
real_ip_header X-Forwarded-For;
Restart nginx and then you can test it by running the tail command and loading your web page to see new access logs. DONE!

Nginx + Varnish

If you are using nginx + varnish the guide above will not work for you. If you view your access logs you will be presented with localhost (127.0.0.1) instead of your loadbalancers IP address. To resolve this issue you will add the following lines to /etc/nginx/nginx.conf:

set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
This will change your logs similar to the following example:

Example:

Before – 127.0.0.1 – – [09/Jan/2015:20:40:00 +0000] “GET

After – 10.189.246.5 – – [09/Jan/2015:20:40:25 +0000] “GET

This will change your log files from 127.0.0.1 to the ip address of your load balancer. Now we will need to change the ip address from your load balancer’s to the visitors ip address.

You can do this by editing /etc/varnish/default.conf file and making sure you have the following code in the sub vcl_recv { section:

if (req.restarts == 0) {

if (!req.http.x-forwarded-for) {
set req.http.X-Forwarded-For = client.ip;
}
}
A larger example of this config section:

sub vcl_recv {

if (req.restarts == 0) {
if (!req.http.x-forwarded-for) {
set req.http.X-Forwarded-For = client.ip;
}
}

if (req.request != "GET" &&
req.request != "HEAD" &&
req.request != "PUT" &&
req.request != "POST" &&
....
Restart nginx and varnish and your done!

x-forwarded-for_centos_nginx.txt · Last modified: 2024/05/23 07:26 by 127.0.0.1