我有一个 NestJS 服务器,它部署在带有 nginx 的 EC2 实例上。我想从请求发起的地方获取客户端 IP 地址,但我在每个请求中都得到“127.0.0.1”作为 ip,无论它来自哪里。
我尝试直接从请求标头获取ip,并使用nestjs中的@Ip装饰器。但仍然获得相同的IP。
我也尝试过在 nginx 配置中设置标头,就像这样。
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:5001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
在
main.ts
的 bootstrap
方法中,在 app.listen()
之前添加此行
app.getHttpAdapter().getInstance().set("trust proxy", true);
这将告诉express信任代理IP并允许您正确使用
req.ip
或@Ip()
装饰器