nginx set X-Real-IP to downstream proxied servers to prevent spoofing
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?
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;
}