Linux 4 All

Best Linux tricks source

Posts in the LogFormat category

When Nginx is running on a server behind a Load Balancer, by default all traffic will come from Load Balancer IP, thus Nginx will only log the Load Balancer IP. In order to get your visitor real IP address, you can use X-Forwarded-For header.

In order to configure Nginx to log real IP address, add the following to nginx.conf, http section:

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    set_real_ip_from 127.0.0.1; # Varnish IP address
    set_real_ip_from 10.0.0.0/8; # Load Balancer IP range

    real_ip_header X-Forwarded-For;
    real_ip_recursive on;

When Apache is running on a server behind a Load Balancer, by default all traffic will come from Load Balancer IP, thus Apache will only log the Load Balancer IP. In order to get your visitor real IP address, you can use X-Forwarded-For header.

Here is how Apache needs to be configured to log real IP addresses:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" forwarded
SetEnvIf X-Forwarded-For "." forwarded=1
CustomLog logs/access_log combined env=!forwarded
CustomLog logs/access_log forwarded env=forwarded

Basically you were adding a new LogFormat with X-Forwarded-For value named forwarded and configure CustomLog to use combined if the request was sent directly to the server: such as a curl cronjob, or forwarded if the request was passed through the Load Balancer.