如何解决通过 Docker 容器和 Nginx 网络服务器在 Laravel 中获取用户的 IP 地址
美好的一天,
我的问题是,当使用 Laravel 的 $request->ip()
或 $request->getClientIp ()
或 $request->server->get('REMOTE_ADDR')
或 $_SERVER['REMOTE_ADDR']
时,我仅获取我的 Docker 网络 IP 地址基本上都做同样的我假设。
到目前为止,问题出现在我的本地测试电脑(没有 Nginx 反向代理)以及我的实时服务器上
我希望我在下面提供了足够的相关信息,如果没有,请告诉我:) 提前致谢!
所以我的设置如下(简化),两个 Nginx 配置也粘贴在下面:
Server -> Nginx Reverse Proxy -> Docker Containers & Network (db,php,nginx,redis) -> Nginx Webserver <-> PHP-FPM
一些与_SERVER相关的结果:
[SERVER_ADDR] => 172.20.0.3 (nginx webserver)
[REMOTE_PORT] => 55378
[REMOTE_ADDR] => 172.20.0.1 (docker network / gateway)
[SERVER_SOFTWARE] => nginx/1.19.6
在尝试和更改配置等时,我已经阅读了多个论坛和解决方案数小时,但似乎没有一个有效。
我尝试过的:
- Get User IP address in laravel with similar method to HTTP_X_FORWARDED_FOR
- https://serverfault.com/questions/618456/getting-the-client-ip-when-passing-through-a-reverse-proxy
所以我也尝试在 Laravel 的 /Http/Middleware/TrustProxies.php
中设置我的“可信代理”,允许所有:protected $proxies = '*';
从 5.5 开始,我也不需要这些额外的 Laravel 包,我相信这是 Laravel (TrustProxies) 的内置功能。
请在下面找到我的 Nginx 网络服务器配置:
server {
listen 80;
server_name domain.com;
return 301 https://www.example.com;
}
server {
listen 80 default_server;
index index.html index.htm index.php;
server_name www.example.com;
root /var/www/public;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-fpm:9013;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/example.com/public/$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
# Support Clean (aka Search Engine Friendly) URLs & enable Gzip compression:
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
# Override the load balancer IP with real IP.
fastcgi_param REMOTE_ADDR $http_x_real_ip;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
}
和我的服务器的 Nginx 反向代理配置(如果相关):
server {
listen 80;
listen [::]:80;
server_name example.com.au www.example.com.au;
location / {
proxy_pass http://localhost:8013;
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_set_header X-Forwarded-Host $server_name;
}
}
解决方法
好的明白了! :D
-
我使用 Cloudflare 作为代理,我的 DNS 使用 CloudFlare,并且由于速度/缓存改进,我启用了“通过 CloudFlare 代理”选项。 这导致 CloudFlare “注入”了一个
HTTP_CF_CONNECTING_IP
到我的标头中。 为了检索此标头值,我在代码中使用了$_SERVER['HTTP_CF_CONNECTING_IP']
。 -
另一种解决方案是通过使用
HTTP_X_FORWARDED_FOR
来使用标头中的_SERVER['HTTP_X_FORWARDED_FOR']
值,我相信这在我的情况下只有在执行以下操作后才有效(发布在我的问题中):
- TrustProxies.php
- proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
我希望这也能帮助其他人:D
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。