Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: directly return $remote_addr in text/plain

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?

like image 249
kenn Avatar asked Aug 20 '15 00:08

kenn


People also ask

What is Default_server in Nginx?

In the configuration above, the default server is the first one — which is nginx's standard default behaviour. It can also be set explicitly which server should be default, with the default_server parameter in the listen directive: server { listen 80 default_server; server_name example.net www.example.net; ... }

What is Client_max_body_size in Nginx?

client_max_body_size 1m; Context: http , server , location. Sets the maximum allowed size of the client request body. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client.

What is Keepalive_timeout in Nginx?

Context: http , server , and location. This directive defines the number of seconds the server will wait before closing a keep-alive connection. The second (optional) parameter is transmitted as the value of the Keep-Alive: timeout= <HTTP response header> .

What is Send_timeout in Nginx?

Context: http , server , location. The number of time after which Nginx closes an inactive connection. A connection becomes inactive the moment a client stops transmitting data. Syntax: Time value (in seconds)


2 Answers

The simplest way is:

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

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

like image 195
Andrei Belov Avatar answered Oct 11 '22 23:10

Andrei Belov


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)
    ';
}
like image 38
fannheyward Avatar answered Oct 12 '22 01:10

fannheyward