1、获取计算机 公网真实IP 方法。
fetch ('https://api.ipify.org/?format=json')
.then(response => response.json())
.then(data => console.log('Public IP:', data.ip))
.catch(error => console.error('Error fetching public IP:', error));
验证办法:
mac电脑终端、windows电脑CMD输入:
curl ipinfo.io/ip
2、获取计算机 局域网真实IP 方法。
在Nginx中,可以通过使用$remote_addr
变量来获取客户端的真实IP地址。
如果需要将该值传递到后端服务器(比如PHP)进行处理,则可以使用proxy_set_header
指令设置HTTP头部信息,并将其发送至后端服务器。示例配置如下所示:
# 放在: location ^~/api { } 中
location ^~/api {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering off;
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://backend_server; #后端地址:http://198.163.2.1:1000
}
# 注意:放在其他地方可能不生效。
当有请求经过Nginx时,会将客户端的真实IP地址作为名为"X-Real-IP"的自定义HTTP头部字段传递给后端服务器。
前、后端配合才能实现IP显示问题。
注意:上述配置仅适用于反向代理场景,若直接连接到后端服务器而不经过Nginx,则无法获得客户端真实IP地址。