My environment: Ubuntu 18.04, Asp.net Core 2.1, Nginx
I followed this tutorial. I added this code in Startup.cs:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
I configure my Nginx configuration:
listen *:443 ssl http2;
location / {
proxy_pass https://localhost:6001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-Proto-Version $http2;
client_max_body_size 32m;
keepalive_timeout 200;
send_timeout 20;
client_body_timeout 50;
proxy_set_header X-Forwarded-For $remote_addr;
}
I get the remote IP by:
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
but it always returns 127.0.0.1 from any IP.
I personally had to get header value manually. It was due to the cloud setting. Maybe this will help you.
if (Request.Headers.TryGetValue("X-Forwarded-For", out var forwardedIps))
senderIpv4 = forwardedIps.First();
You forgot proxy_set_header X-Forwarded-Proto $scheme;
in your nginx configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With