一、使用X-Forwarded-For
- 使用X-Forwarded-For记录真实IP,用于快速取得用户的真实IP
- X-Real-IP 也是记录真实IP,但是他只记录上一级的IP,如果有多级代理他就不准了
一级代理 | 192.168.200.120 |
二级代理 | 192.168.200.121 |
web | 192.168.200.122 |
一级代理配置
[root@nginx ~]# vim /etc/nginx/conf.d/test-01.conf
server {
listen 80;
server_name www.test-01.org;
location / {
proxy_pass http://192.168.200.121:80;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
~
二级代理配置
[root@nginx ~]# vim /etc/nginx/conf.d/test-01.conf
server {
listen 80;
server_name www.test-01.org;
location / {
proxy_pass http://192.168.200.122:80;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
web配置
[root@nginx conf.d]# vim test.conf
server {
listen 80;
server_name www.test-01.org;
root /code/test;
location / {
index index.html;
}
}
访问查看日志记录的IP地址
[root@nginx ~]# tailf /var/log/nginx/access.log
192.168.200.121 - - [19/Jun/2023:19:51:33 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0" "192.168.200.10, 192.168.200.120"
二、使用realip的方式记录真实IP
- 使用nginx Realip_module获取多级代理下的真实ip,在web节点配置
[root@nginx conf.d]# vim test.conf
server {
listen 80;
server_name www.test-01.org;
root /code/test;
set_real_ip_from 192.168.200.120; # 一级代理的IP地址
set_real_ip_from 192.168.200.121; # 二级代理的IP地址
real_ip_header X-Forwarded-For; # 从哪个header头检索需要的IP地址
real_ip_recursive on; # 排除set_real_ip_from出现的IP,剩余的就是真实IP
location / {
index index.html;
}
}
[root@nginx ~]# systemctl reload nginx.service
- 测试查看访问日志
- 跟上面的区别就是:首IP是真实ip,那么程序员就可以通过remot_addr得到真实ip地址
[root@nginx ~]# tailf /var/log/nginx/access.log
192.168.200.10 - - [19/Jun/2023:20:02:42 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0" "192.168.200.10, 192.168.200.120"