Skip to content

Instantly share code, notes, and snippets.

@majudhu
Last active September 6, 2022 18:07
Show Gist options
  • Save majudhu/221e30214d9ac7cdfb0fc002622bbe4a to your computer and use it in GitHub Desktop.
Save majudhu/221e30214d9ac7cdfb0fc002622bbe4a to your computer and use it in GitHub Desktop.
cloudflare nginx real ip expressjs req.ip trust_proxy
proxy_headers_hash_max_size 1024;
proxy_headers_hash_bucket_size 128;
# https://www.cloudflare.com/ips/
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
real_ip_header CF-Connecting-IP;
server {
server_name example.com;
# dynamic cloudflare ip list, fallback to $remote_addr if not from cloudflare
location /api/ {
proxy_pass http://127.0.0.1:3000/;
include proxy_params;
include cf_real_ip;
}
# avoid ip list, site guaranteed to be accessible over cloudflare only, otherwise assume request is from a trusted source anyway
location /api/ {
proxy_pass http://127.0.0.1:3000/;
include proxy_params;
proxy_set_header X-Forwarded-For $http_cf_connecting_ip;
}
# no cloudflare
location /api/ {
proxy_pass http://127.0.0.1:3000/;
include proxy_params;
}
}
# log format with cloudflare
log_format with_cf '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $http_x_forwarded_for $http_cf_ipcountry $http_cf_ray $http_cf_connecting_ip';
access_log /var/log/nginx/access.log with_cf;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment