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?
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; ... }
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.
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> .
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)
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.)
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)
';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With