美文网首页
通过nginx显示client的公网IP

通过nginx显示client的公网IP

作者: 遇酒无缘 | 来源:发表于2019-11-18 11:28 被阅读0次

    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.

    来自于:https://www.ecalamia.com/blog/show-ip-api-nginx/

    相关文章

      网友评论

          本文标题:通过nginx显示client的公网IP

          本文链接:https://www.haomeiwen.com/subject/ltvvictx.html