大网数据广告活动
服务器运维问答

nginx set X-Real-IP to downstream proxied servers to prevent spoofing

· 52CE 我爱测

I'm wanting to correctly set X-Real-IP for domains proxied by nginx that also sit behind an amazon ELB. i.e. AMAZON ELB <=> NGINX PROXY <=> REST APP1 <=> REST APP2 So far, I've found the following correctly works and prevents spo…

问题原文

原帖链接 · hookenz · CC BY-SA 3.0

I'm wanting to correctly set X-Real-IP for domains proxied by nginx that also sit behind an amazon ELB.

i.e.

AMAZON ELB <=> NGINX PROXY <=> REST APP1
                           <=> REST APP2

So far, I've found the following correctly works and prevents spoofing the IP. I have this set globally in nginx.conf

real_ip_header X-Forwarded-For;
set_real_ip_from 10.0.0.0/8;
real_ip_recursive on;

However, I also have some REST apps that sit behind the NGINX

My rest apps will use x-real-ip if set or x-forwarded-for. Under normal use, the real client IP is correct.

Under a spoofed IP attack where one or both of the x-real-ip and x-forwarded-for headers are set, I see the spoofed IP in the REST client. However, nginx shows the correct client IP.

Currently in domain host I have set

proxy_pass_request_headers on;

How do set the x-real-ip to be the real trusted IP for the REST apps?

I presume I need a proxy_set_header line with X-Real-IP. But how do I reference what the the real-ip header is set by the real-ip module?

已采纳解答

原帖链接 · hookenz · CC BY-SA 3.0

I found the answer.

I had been trying to set the following directives which I found on the web. But it didn't seem to work.

proxy_set_header X-Real-IP       $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

After some messing around I thought I'd try placing them in a location block. I had tried placing them in the html section and also the server section. However, if you place the above in location block like below it will work. e.g.

location / {
   proxy_pass http://localhost:1234;
   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_pass_request_headers on;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-03-31)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。