When using BunnyCDN as a CDN or reverse proxy, your web server (Nginx, Apache) only sees the IP address of BunnyCDN’s edge servers, not the real IP of your visitors. This can cause issues with logging, security modules (like ModSecurity), and IP-based features.
In this guide, you’ll learn how to restore the real visitor IP in Nginx when using BunnyCDN.
Why Restore Real IPs?
- Accurate Logging: Log files will show the real visitor IP, not BunnyCDN’s IP.
- Security: will work correctly.
- GeoIP: will use the correct visitor location.
How BunnyCDN Forwards Real IPs
BunnyCDN adds the real visitor IP in the X-Real-IP HTTP header. To restore the real IP in Nginx, you need to:
- Trust BunnyCDN’s IP ranges (so Nginx knows which IPs are from BunnyCDN).
- Configure Nginx to use the
X-Real-IPheader.
Step 1: Fetch BunnyCDN’s IP Ranges
BunnyCDN provides a list of their edge server IPs at:
Step 2: Configure Nginx
Since , it’s best to automate the process with a script.
#!/usr/bin/env bash
# Purpose: Update Nginx with BunnyCDN IPs (using jq)
# -------------------------------------------------------------------
set -e
# IP List
IPv4="https://bunnycdn.com/api/system/edgeserverlist"
IPv6="https://bunnycdn.com/api/system/edgeserverlist/IPv6"
# Nginx config file (separate include file)
conf="/etc/nginx/conf.d/bunnycdn.conf"
# Path to nginx binary
nginx_cmd="/usr/sbin/nginx"
file="/tmp/ips.$$"
# Clear the config file
echo "" > "${conf}"
# Fetch and parse IPv4
echo "Fetching IPv4 IPs..."
wget -q "${IPv4}" -O - | jq -r '.[]' > "${file}"
# Fetch and parse IPv6
echo "Fetching IPv6 IPs..."
wget -q "${IPv6}" -O - | jq -r '.[]' >> "${file}"
# Count the IPs
ip_count=$(wc -l < "${file}")
echo "Found ${ip_count} IPs."
echo "real_ip_header X-Real-Ip;" >> "${conf}"
# Add set_real_ip_from directives to the config file
while read -r i
do
echo "set_real_ip_from ${i};" >> "${conf}"
done < "${file}"
# Check the config file
echo "Config file content:"
cat "${conf}"
# Check for syntax error and reload the nginx
echo "Testing Nginx config..."
if ${nginx_cmd} -qt; then
echo "Nginx config is valid. Reloading..."
${nginx_cmd} -s reload
else
echo "Nginx config test failed. Not reloading."
exit 1
fi
# Clean up
rm -f "${file}"
Save this script as /usr/local/bin/update_bunnycdn_ips.sh:
Make the Script Executable
chmod +x /usr/local/bin/update_bunnycdn_ips.shInclude in Nginx
Add this line to your main nginx.conf (inside the http block):
real_ip_header X-Real-IP;real_ip_recursive on;include /etc/nginx/conf.d/bunnycdn.conf;Run the Script
/usr/local/bin/update_bunnycdn_ips.shAutomate with Cron
Add a cron job to run the script daily:
crontab -eAdd:
0 3 * * * /usr/local/bin/update_bunnycdn_ips.shConclusion
By following this guide, you’ve configured Nginx to restore the real IP of visitors behind BunnyCDN. This ensures accurate logging, security, and IP-based features.
Bildquellen
- icon-7823205_1920: Pixaby