You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署在EC2+Nginx的NestJS服务获取客户端IP始终为127.0.0.1求助

解决NestJS通过Nginx反向代理时获取真实客户端IP的问题

你的Nginx配置已经正确添加了转发客户端IP的请求头,但NestJS默认不会信任这些来自代理的头信息,所以始终返回127.0.0.1。按以下步骤解决:

  • 配置NestJS信任代理服务器
    在项目的main.ts中启用信任代理,指定Nginx所在的IP(这里是本地127.0.0.1):

    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      // 信任本地的Nginx代理
      app.enableTrustProxy('127.0.0.1');
      await app.listen(5001);
    }
    bootstrap();
    

    生产环境建议明确指定信任的代理IP,避免安全风险;如果需要信任所有代理,可传入true。

  • 正确获取客户端IP
    两种可靠方式:

    1. 使用NestJS的@Ip装饰器(启用信任代理后会自动解析真实IP):
      import { Controller, Get, Ip } from '@nestjs/common';
      
      @Controller()
      export class AppController {
        @Get('check-ip')
        getClientIp(@Ip() ip: string) {
          return { client_ip: ip };
        }
      }
      
    2. 从请求头解析X-Forwarded-For(该字段可能包含多个IP,第一个为原始客户端IP):
      import { Controller, Get, Req } from '@nestjs/common';
      import { Request } from 'express';
      
      @Controller()
      export class AppController {
        @Get('check-ip')
        getClientIp(@Req() req: Request) {
          const forwardedIp = req.headers['x-forwarded-for'];
          // 处理多个IP的情况,取第一个有效IP
          const clientIp = typeof forwardedIp === 'string' 
            ? forwardedIp.split(',')[0].trim() 
            : req.ip;
          return { client_ip: clientIp };
        }
      }
      
  • 验证Nginx配置生效
    重启Nginx服务使配置生效:

    sudo systemctl restart nginx
    

    可以查看Nginx的访问日志(通常在/var/log/nginx/access.log),确认$remote_addr记录的是客户端真实IP,而非127.0.0.1。

内容的提问来源于stack exchange,提问作者Faisal Anwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:31:00