3

Nginx获取真实的客户端IP和限制IP

 1 year ago
source link: https://www.daguanren.cc/post/Nginx-huo-qu-zhen-shi-de-ke-hu-duan-IP-he-xian-zhi-IP.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Nginx获取真实的客户端IP和限制IP

有时候,我们的服务会经过多层nginx代理转发。比如一个www.daguanren.cc这个服务部署在服务器A上,

经过反向代理后,由于在客户端和web服务器之间增加了中间层,因此web服务器无法直接拿到客户端的ip,通过$remote_addr变量拿到的将是反向代理服务器的ip地址。

X-Forwarded-For:这个头部设置了客户端IP,以及每一级代理IP(形式为:clinet_ip, proxy1_ip, proxy2_ip, 需要在代理层配置) REMOTE_ADDR:上一级代理服务的IP,若上一级代理为空,即为客户端IP。

在真实场景中,我们以Nginx代理服务器、Node.js服务为例:客户端 >>>> Nginx >>>> Node.js在第一级代理处增加配置:server { listen 8443; server_name xxx.xxx.com; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_pass your Node.js servecrmsh

效果是:http头中会增加 x-real-ip 这个字段,并被Nginx赋值为客户端地址。Node.js通过读取http header中的 x-real-ip 即可获取客户端真实IP地址。

假如存在多级代理,即Nginx --> Nginx --> web服务,需这样处理:

a. 在第一层Nginx代理中配置: proxy_set_header x-real-ip $remote_addr; b. 第二层Nginx代理中则不添加该条配置 然后在web服务中直接从http头中读出x-real-ip这个字段作为ip地址即可。

https://www.jianshu.com/p/01e08c6eb85e

https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node

https://amos-x.com/index.php/amos/archives/nginx-realip/

https://blog.csdn.net/qq_34556414/article/details/106634895

IP限制的写法

server { listen 80; server_name www.daguanren.cc; allow 11.64.10.174; allow 127.0.0.1; allow 11.20.0.182; allow 47.4.18.240; allow 12.13.15.5; allow 9.32.35.18; allow 154.8.27.12; deny all; location / { # proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0'; root /home/erp/; index index.html;nginx
#只允许指定的ip访问a1.htm a2.htm a3.htm这个三个页面,其他IP的访问都拒绝location ~* /(a1.htm|a2.htm|a3.htm)$ { allow 10.0.0.2; deny all; condition………;armasm

https://www.yisu.com/zixun/148142.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK