Nginx: directly return $remote_addr in text/plain
Asked Answered
D

4

26

It may sound like a code golf question, but what is the simplest / lightest way to return $remote_addr in text/plain?

So, it should return several bytes of the IP address in a plain text.

216.58.221.164

Use case: An API to learn the client's own external (NAT), global IP address.

Is it possible to do it with Nginx alone and without any backends? If so, how?

Dialytic answered 20/8, 2015 at 0:53 Comment(0)
P
57

The simplest way is:

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

The above should be added to the server block of your nginx.conf.

No need to use any 3rd party module (echo, lua etc.)

Periostitis answered 20/8, 2015 at 6:35 Comment(1)
Perfect, that's what I wanted exactly. :)Dialytic
K
4

Here's an approach you can use to consider proxied connections:

# 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";
    }
}
Keos answered 15/1, 2021 at 21:37 Comment(0)
D
2

Use ngx_echo:

location /ip {
    default_type  text/plain;
    echo $remote_addr;
}

Use ngx_lua:

location /b {
    default_type  text/plain;
    content_by_lua '
        ngx.say(ngx.var.remote_addr)
    ';
}
Detection answered 20/8, 2015 at 1:25 Comment(0)
O
0

A long time ago I made a practice always to add ip.example.com to most of my servers with the following configuration:

/etc/nginx/sites-enabled$ cat ip
server {
    server_name ip.*;

    root       /dev/null;
    access_log /dev/null;
    error_log  /dev/null;

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

It's really helpful for checking VPN, networks, remote accesses, scripting, etc... You can use it in the browser directly or curl in cli...

Ohaus answered 12/3 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.