Created
March 17, 2023 02:05
-
-
Save eaguad1337/31a9e81d4ec6862c6c1fc253c1002bbe to your computer and use it in GitHub Desktop.
Enable Real IP in Nginx behind Cloudflare
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if nginx is installed | |
echo "Check if nginx is installed" | |
if [[ $(dpkg-query -W -f='${Status}' nginx 2>/dev/null | grep -c "ok installed") -eq 0 ]]; then | |
echo "nginx is not installed" | |
exit 1 | |
fi | |
echo "Check if http_realip_module and realip_module are active in nginx" | |
# check if http_realip_module and realip_module are active in nginx | |
if [[ $(nginx -V 2>&1 | grep -o 'http_realip_module') != "http_realip_module" ]]; then | |
echo "http_realip_module is not enabled" | |
exit 1 | |
fi | |
if [[ $(nginx -V 2>&1 | grep -o 'realip_module') != "realip_module" ]]; then | |
echo "realip_module is not enabled" | |
exit 1 | |
fi | |
echo "Append configuration to nginx.conf" | |
sed -i -e '/set_real_ip_from/d' -e '/real_ip_header/d' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 173.245.48.0/20;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 103.21.244.0/22;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 103.22.200.0/22;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 103.31.4.0/22;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 141.101.64.0/18;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 108.162.192.0/18;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 190.93.240.0/20;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 188.114.96.0/20;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 197.234.240.0/22;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 198.41.128.0/17;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 162.158.0.0/15;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 104.16.0.0/13;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 104.24.0.0/14;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 172.64.0.0/13;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ set_real_ip_from 131.0.72.0/22;' /etc/nginx/nginx.conf | |
sed -i '/http {/a\ real_ip_header CF-Connecting-IP;' /etc/nginx/nginx.conf | |
# test if nginx configuration is ok | |
if [[ $(nginx -t 2>&1 | grep -o 'successful') != "successful" ]]; then | |
echo "nginx configuration is not ok" | |
exit 1 | |
fi | |
# restart nginx | |
echo "Restart nginx" | |
systemctl restart nginx | |
echo "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment