您当前的位置:首页 > 计算机 > 服务器 > Nginx

Public IP Address API with two lines of Nginx config

时间:12-14来源:作者:点击数:

Here is how I set up a "show my public IP address" with Nginx without any backend (no PHP, no Nginx-Lua, ...).

The following block does the trick:

location /ip {
    default_type text/plain;
    return 200 $remote_addr;
}

The response is simply the IP address of the client:

$ curl https://example.com/ip
2001:1b48:103::189

The default_type text/plain directive has no utility other than preventing Web browsers from attempting to download the response as a file. That is, a Web browser can display the IP address directly.

For programs interacting with the endpoint, it has no particular utility.

Bonus: JSON response

Want a JSON response? Sure, it is perfectly doable:

location /json_ip {
    default_type application/json;
    return 200 "{\"ip\":\"$remote_addr\"}";
}

The response is now a pretty JSON document:

$ curl -s https://example.com/json_ip | jq
{
    "ip": "2001:1b48:103::189"
}

I hope that little Nginx trick will save you some maintenance time.

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐