問題:
? ? ? ? 如題
參考:
????????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<NestExpressApplication>(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<NestExpressApplication>(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));}
}