X-Forwarded-For 是一个 HTTP 头部字段,用于记录客户端 IP 地址。当请求通过代理服务器(如 Nginx)转发到上游服务器时,原始客户端的 IP 地址可能会被隐藏。为了获取真实的客户端 IP 地址,可以在 Nginx 配置中使用 X-Forwarded-For 头部字段。
以下是如何在 Nginx 配置中使用 X-Forwarded-For 的示例:
打开 Nginx 配置文件,通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/your_domain.conf。
在 server 或 location 块中,添加以下配置:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
这行配置会将客户端的 IP 地址添加到 X-Forwarded-For 头部字段中,并将其传递给上游服务器。
proxy_set_header X-Real-IP $remote_addr;
这行配置会将客户端的真实 IP 地址添加到 X-Real-IP 头部字段中,并将其传递给上游服务器。
sudo nginx -t
sudo service nginx restart
X-Forwarded-For 或 X-Real-IP 头部字段来获取客户端的真实 IP 地址。例如,在 PHP 中:
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
在 Python(使用 Flask 框架)中:
from flask import request
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
在 Node.js(使用 Express 框架)中:
const express = require('express');
const app = express();
app.use((req, res, next) => {
const client_ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
req.client_ip = client_ip;
next();
});
现在,你可以在应用程序中使用 client_ip 变量来获取客户端的真实 IP 地址。