带有http2的nginx背后的asp.net核心 - 远程ip总是127.0.0.1

时间:2018-05-03 20:27:10

标签: nginx asp.net-core ip-address http2

我在Ubuntu 16.04上有一个在Nginx后面托管的asp.net net core 2.0应用程序。

我的设置如下:

server {
        listen 443 ssl http2; 
        listen [::]:443 ssl http2;
        ssl on;
...
    location / {
                    proxy_pass http://localhost:5000;
                    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;
            }
}

我在Startup.cs

中也有这些设置
app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                   ForwardedHeaders.XForwardedProto
            });

但是每当我试图获得HttpContext.Connection.RemoteIpAddress时,它都会返回127.0.0.1

我该怎么做才能解决这个问题并获得真正的IP地址?

1 个答案:

答案 0 :(得分:3)

好吧,自己找答案。

此行不需要(但似乎不做任何有害的事情)

declare @holding table (country1 varchar(max), country2 varchar(max), rank int)
declare @iterator int=1
declare @countrylistoriginal1 varchar(max) 
declare @countrylistoriginal2 varchar(max) 
declare @countrylist1  varchar(max) 
declare @countrylist2  varchar(max) 
declare @rank  int 
while @iterator<=(select max(rowid) from #temp2)
begin
select @countrylistoriginal1=countrylist1+'|',  @rank=[rank] 
from yourtable where rowid=@iterator
while @countrylistoriginal1<>''  
begin
set @countrylist1=left(@countrylistoriginal1,(charindex('|',@countrylistoriginal1)))
set @countrylistoriginal1=replace(@countrylistoriginal1, @countrylist1,'')
select @countrylistoriginal2=countrylist2+'|'  
from yourtable where rowid=@iterator
while @countrylistoriginal2<>''   
begin 
set @countrylist2=left(@countrylistoriginal2,(charindex('|',@countrylistoriginal2)))
set @countrylistoriginal2=replace(@countrylistoriginal2, @countrylist2,'')
insert @holding
select replace(@countrylist1,'|',''), replace(@countrylist2,'|',''), @rank
end
end
set @iterator=@iterator+1
end

select distinct  a.country1,  a.rank from @holding a
left join @holding b on a.country1=b.country2 and a.rank=b.rank where b.country2 is null

但是我们需要告诉Nginx用这一行设置proxy_set_header X-Forwarded-Proto-Version $http2; 标题:

<强> X-Forwarded-For