By default, when you place Nginx behind Cloudflare, the http_remote_addr in access_log will contain the Cloudflare IP, which is not what we want.
To enable Nginx to resolve the real IP of visitors, we need to whitelist the Cloudflare IPs and map the header value.
To automate this process, we can write a bash script that handles this repetitive task.
Assuming you are using Ubuntu or Debian-based systems, where Nginx automatically loads configuration files from /etc/nginx/conf.d, you can simply run bash /etc/nginx/cloudflare-ip-whitelist-sync.sh to enable the real IP from Cloudflare.
Here’s a sample content of /etc/nginx/conf.d/cloudflare.conf:
Since Cloudflare may update their IP addresses, it’s best practice to stay synced with them. We can set a cron job for this script to run every day at 1 am.