nginx

Nginx: Log client ip behind NAT with http_x_forwarded_for (X-Forwarded-For Header)

Use nginx real_ip module
nginx -V | grep with-http_realip_module
# /etc/nginx/nginx.conf
...
http {
...
# set_real_ip_from 0.0.0.0/0;
set_real_ip_from x.x.x.x/x; # LB subnet
real_ip_header X-Forwarded-For;
...
}
...

Option 2: customize log_format
cat /etc/nginx/nginx.conf
...
log_format main '$http_x_forwarded_for - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
...

Reload Nginx configuration

Nginx (proxy) Docker container

Create required directories
mkdir -p /etc/docker/nginx/{conf.d,html}

Configure nginx as webserver
cat < /etc/docker/nginx/conf.d/default.conf
server {
listen 80;
server_name _;

root /usr/share/nginx/html;
index index.html index.htm;
}
EOF

Configure nginx as proxy
cat < /etc/docker/nginx/conf.d/proxy.conf
server {
listen 80;
server_name foo.example.com;

location / {
proxy_pass http://localhost:8080/;
}
}
EOF

Create container

Nginx access control / GeoIP

cat < /etc/nginx/conf.d/geoip.conf
geoip_country /usr/share/GeoIP/GeoIP.dat;

map $geoip_country_code $allowed_country {
default no;
DE yes;
CH yes;
}

log_format allow "allow $remote_addr;";
EOF
chmod 644 /etc/nginx/conf.d/geoip.conf

cat < /usr/local/bin/nginx-allow
#!/bin/bash

while inotifywait --quiet --event create,delete --exclude "[^c][^o][^n][^f]$" /tmp
do
/usr/sbin/nginx -t && /usr/sbin/service nginx reload
done
EOF
chmod 755 /usr/local/bin/nginx-allow

cat < /etc/systemd/system/nginx-allow.service
[Unit]

nginx

Modules
# List modules
nginx -V

Sites
# /etc/nginx/sites-available/www.example.com.conf
server {
server_name www.example.com;
listen 443 ssl;

root /usr/share/nginx/www/;

ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;

sub_filter_once off;
sub_filter "Welcome" "Sello";
}

server {
server_name www.example.com;
listen 80;

root /usr/share/nginx/www/;

access_log /var/log/nginx/access_www.example.com.log;