Nginx:直接返回文本/纯文本格式的$remote_addr

rsl1atfo  于 2022-11-02  发布在  Nginx
关注(0)|答案(3)|浏览(240)

这听起来可能像是一个代码高尔夫问题,但是在text/plain中返回$remote_addr的最简单/最轻松的方法是什么?
因此,它应该以纯文本形式返回IP地址的几个字节。

216.58.221.164

使用案例:一个API,用于获取客户端自己的外部(NAT)全局IP地址。
有没有可能在没有任何后端的情况下单独使用Nginx来完成它?如果有,怎么做?

eqfvzcg8

eqfvzcg81#

最简单的办法是:

location /remote_addr {
    default_type text/plain;
    return 200 "$remote_addr\n";
}

上述内容应添加到nginx.confserver块中。
无需使用任何第三方模块(echo、lua等)

qrjkbowd

qrjkbowd2#

下面是一种可以用来考虑代理连接的方法:


# 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";
    }
}
ttvkxqim

ttvkxqim3#

使用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)
    ';
}

相关问题