[nginx]借助nginx实现自动获取本机IP

前言

在用脚本自动化部署应用时,有的应用需要指定本机IP,网上找到的方案大多是过滤ifconfig或者ip命令的结果,这里提供一种通过nginx获取本机ip的方法。大致思路为客户端向nginx发起请求,nginx返回客户端的ip。

nginx配置

nginx安装在内网,返回IP的配置如下:

server {
	...
	location /ip {
		add_header Content-Type 'text/html; charset=utf-8';
        return 200 "$remote_addr";
	}

}

配置生效:

# 这里使用热加载,也可以直接重启
nginx -s reload

测试

假设nginx的ip和端口为 http://192.168.0.20:1234,客户端使用curl发起请求:

curl http://192.168.0.20:1234/ip

脚本示例

#!/bin/bash

local_ip=$(curl -s http://192.168.0.20:1234/ip)
echo "本机IP为: ${local_ip}"
posted @ 2022-09-02 09:25  花酒锄作田  阅读(993)  评论(0编辑  收藏  举报