在服务器端开发中,经常碰到需要获取IP的情况,熟悉后端语言的同学可能很快就使用代码来实现, 然后配置一个接口返个客户端,其实使用nginx可以很容易实现这个获取IP的功能。
1.Nginx可以很容易获取客户端的IP,配置如下:
location /ip { default_type text/plain; return 200 $remote_addr; }
客户端curl模拟:
$ curl https://example.com/ip 2001:1b48:103::189
2. 返回Json格式
location /json_ip { default_type application/json; return 200 "{\"ip\":\"$remote_addr\"}"; }
客户端curl模拟:
$ curl -s https://example.com/json_ip | jq
{
"ip": "2001:1b48:103::189"
}