这可能听起来像是一个代码高尔夫问题,但在$remote_addr
中返回text/plain
的最简单/最轻的方式是什么?
因此,它应该以纯文本形式返回IP地址的几个字节。
216.58.221.164
用例:用于了解客户端自己的外部(NAT)全局IP地址的API。
是否可以单独使用Nginx并且没有任何后端?如果是这样,怎么样?
答案 0 :(得分:16)
最简单的方法是:
location /remote_addr {
default_type text/plain;
return 200 "$remote_addr\n";
}
无需使用任何第三方模块(echo,lua等)
答案 1 :(得分:1)
使用ngx_echo
:
location /ip {
default_type text/plain;
echo $remote_addr;
}
使用ngx_lua:
location /b {
default_type text/plain;
content_by_lua '
ngx.say(ngx.var.remote_addr)
';
}
答案 2 :(得分:0)
您可以使用以下方法来考虑代理连接:
# Map IP address to variable
map ":$http_x_forwarded_for" $IP_ADDR {
":" $remote_addr; # Forwarded for not set
default $http_x_forwarded_for; # Forwarded for is set
}
server {
...
location / {
default_type text/plain;
return 200 "$IP_ADDR";
}
}