如何使用Nginx配置CF-Connecting-IP头?
美国、香港服务器
如何使用Nginx配置CF-Connecting-IP头?
10-13 来源:
### 方案 A:写在 nginx.conf 全局(推荐,全部站点生效)
宝塔 → Nginx → 配置修改,在`http{}`大括号里面添加下面代码
# Cloudflare IPv4 网段
set_real_ip_from 173.245.48.0/20;
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 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
# 核心:读取CF真实IP头
real_ip_header CF-Connecting-IP;
real_ip_recursive on;
### 方案 B:仅单个网站生效(站点配置文件)
宝塔→网站→对应站点→配置文件,在`server {}`内粘贴
注意:只适合单站,多个网站要每个站点都加
set_real_ip_from 173.245.48.0/20;
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 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
real_ip_header CF-Connecting-IP;
real_ip_recursive on;
## 二、配置后校验(必做)
1. 检测语法
nginx -t
输出 `test is successful` 才代表配置语法没问题。
2. 重载 Nginx 生效
nginx -s reload
## 三、日志格式优化(查看真实访客 IP)
宝塔 Nginx 默认日志要修改 log_format,才能记录 CF-Connecting-IP。
在 nginx.conf 的 http 块增加日志格式:
log_format cf_log "$remote_addr [$time_local] "$request" $status "$http_referer" "$http_user_agent" CF_IP:$http_cf_connecting_ip";
站点 server 里指定使用这个日志格式:
access_log /www/wwwlogs/你的域名.log cf_log;
然后访问网站,查看日志验证:
tail -f /www/wwwlogs/你的域名.log
## 四、配套 Nginx 防源 IP 直接访问(一起加上)
放在站点 server 配置:
# 拦截直接用源IP访问
server {
listen 80 default_server;
server_name _;
return 444;
}
三二互联专业提供香港VPS,美国VPS主机,香港云服务器租用等业务香港美国到大陆CN2 GIA速度最快