nestjs:nginx反向代理服务器后如何获取请求的ip地址

问题:

        如题

参考:

        nodejs+nginx获取真实ip-腾讯云开发者社区-腾讯云

        「转」从限流谈到伪造 IP nginx remote_addr

        

解决办法:

1.设置nginx

        对于代理部分,对http header添加Host、X-Real-IP、X-Forwarded-For(最重要)

        

		location /api {
			proxy_set_header Host $http_host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			
			proxy_pass   http://localhost:5000;
			proxy_redirect off;
        }

2.nestjs使用express,启用trust proxy

        需要注意,await NestFactory.create(AppModule);

        需要明确使用NestExpressApplication,虽然nestjs默认express,但是为了调用app.set('trust proxy', true),必须显示声明。

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app: NestExpressApplication = await NestFactory.create(AppModule);
  app.set('trust proxy', true)  //此接口NestExpressApplication才有
  app.use(new HttpRequestMiddleware().use);
  await app.listen(3000);
}
bootstrap().then();

3.可以在Request.ip中获取到值了

/**
 * 自定义请求信息日志记录中间件
 */
import { NextFunction, Request, Response } from 'express';
import { NestMiddleware } from '@nestjs/common';

export class HttpRequestMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    next();

    // 组装日志信息
    const logFormat = {
      httpType: 'Request',
      ip: req.ip.split(':').pop(),
      reqUrl: `${req.headers.host}${req.originalUrl}`,
      reqMethod: req.method,
      httpCode: res.statusCode,
      params: req.params,
      query: req.query,
      body: req.body,
    };

    console.log(JSON.stringify(logFormat));
  }
}

你可能感兴趣的:(nginx,服务器,运维)