问题:
如题
参考:
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),必须显示声明。文章来源:https://www.toymoban.com/news/detail-647945.html
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中获取到值了文章来源地址https://www.toymoban.com/news/detail-647945.html
/**
* 自定义请求信息日志记录中间件
*/
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));
}
}
到了这里,关于nestjs:nginx反向代理服务器后如何获取请求的ip地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!