Nginx只允许Cloudflare IP访问获取真实IP

设置只允许cloudflare IP访问后获取真实访客IP,跟普通套Cloudflare获取真实访客IP的方法不一样。

要使用map指令将客户端的 IP 存储到变量(ie$real_client_ip)中,并在日志中使用该变量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 这些放在配置文件头部---
map $http_x_forwarded_for $real_client_ip {
    ~^(\d+\.\d+\.\d+\.\d+) $1;
    default $http_cf_connecting_ip;
}
# replace the default '$remote_addr' with the '$real_client_ip'
log_format custom_log_format '$real_client_ip - $remote_user [$time_local] '
                             '"$request" $status $body_bytes_sent '
                             '"$http_host" "$upstream_response_time"'
                             '"$http_referer" "$http_user_agent"';
# 这些放在配置文件头部---
server {
  listen 80;
  listen [::]:80;
  server_name example.com;
  include /etc/nginx/allow-cloudflare-only.conf;
  #在生成日志文件后面加上custom_log_format
  access_log /var/log/nginx/access.log custom_log_format;
  #...the rest of your configs here...
}

爱搜源码 » Nginx只允许Cloudflare IP访问获取真实IP

发表评论

发表评论