const app = express();
app.get("/abc", (req, res) => {
const forwardedForHeader = req.get("X-Forwarded-For");
const realIpHeader = req.get("X-Real-IP");
let realIp = null;
if (forwardedForHeader && forwardedForHeader.length > 0) {
// 逗号分隔的IP地址列表,取第一个地址为真实IP
realIp = forwardedForHeader.split(",")[0].trim();
} else if (realIpHeader) {
// 如果X-Forwarded-For未设置,则使用X-Real-IP
realIp = realIpHeader.trim();
}
if (!realIp) {
realIp = req.socket.remoteAddress;
}
logger.info(realIp, "------真实ip------");
})
location ^~ /api {
proxy_pass http://127.0.0.1:1111/a/;
proxy_set_header Host 127.0.0.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
如果没配置,那么就可能拿不到真实ip