我使用Perl'Mojolicious'框架编写了一个API,它通过CORS接收来自其他Web服务器的请求,但是我无法提取请求服务器的IP地址。
像X-Forwarded-For
之类的提取标题只提供客户端的IP地址?在Perl或Mojolicious中有没有办法从IP数据包本身中提取源IP?
使用内置的Mojolicious $self->tx->remote_address
方法不起作用,因为我的API Web服务器位于Nginx反向代理之后。
答案 0 :(得分:1)
我使用自己的助手src_addr
:
use Net::IP::Lite;
$app->helper( src_addr => sub {
my $c = shift;
my $xff = $c->req->headers->header('X-Real-IP') // $c->req->headers->header('X-Forwarded-For') // '';
if($xff) {
for my $ip (reverse split(/[\s,]+/, $xff)) {
next if ! ip_validate($ip);
return $ip;
}
}
return $c->tx->remote_address;
});
在nginx中:
location / {
proxy_read_timeout 300;
proxy_pass http://localhost4:54329/;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto "https";
proxy_set_header X-Forwarded-HTTPS 1;
}