Nginx配置Laravel自定义X-Forwarded-For头部失效问题排查
Hey there, let's work through this step by step to get your real client IP working via the X-Forwarded-For header:
1. Fix Your Nginx Configuration
First, there are two critical issues in your current Nginx setup:
- Typo in the header name: You wrote
x-forwaded-for(missing an 'r') instead of the standardX-Forwarded-For - Wrong directive for PHP-FPM:
proxy_set_headeris meant for reverse proxy setups (usingproxy_pass). Since you're using PHP-FPM viafastcgi_pass, you need to set the header withfastcgi_paraminstead.
Here's the corrected Nginx config:
server { listen 9003; listen [::]:9003; access_log /var/log/nginx/immigration-access.log; error_log /var/log/nginx/immigration-error.log; fastcgi_read_timeout 10000; root /var/www/backend/public; index index.php index.html index.htm; server_name *****; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # Pass the client's real IP to Laravel via X-Forwarded-For fastcgi_param HTTP_X_FORWARDED_FOR $remote_addr; include fastcgi_params; } }
Note: If your server sits behind a load balancer, replace
$remote_addrwith$http_x_forwarded_forto preserve the original client IP from the load balancer's header.
2. Configure Laravel to Trust the Proxy Header
By default, Laravel ignores the X-Forwarded-For header for security reasons. You need to update the TrustProxies middleware to allow this:
Open app/Http/Middleware/TrustProxies.php and adjust the properties:
<?php namespace App\Http\Middleware; use Illuminate\Http\Middleware\TrustProxies as Middleware; use Illuminate\Http\Request; class TrustProxies extends Middleware { // Trust all proxies (restrict to specific IPs if you want stricter security) protected $proxies = '*'; // Specify which proxy headers Laravel should use protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO; }
For Laravel 10+, you can also just add TRUSTED_PROXIES=* to your .env file instead of editing the middleware directly.
3. Test the Updated Setup
Now you can test both direct header access and Laravel's built-in IP resolver (which will now respect the X-Forwarded-For header):
public function test() { // Get the header directly $headerIp = request()->header('X-Forwarded-For'); // Let Laravel resolve the correct client IP (recommended approach) $laravelIp = request()->ip(); dd($headerIp, $laravelIp); }
Don't forget to reload Nginx (sudo systemctl reload nginx) and clear Laravel's config cache (php artisan config:clear) to apply all changes.
内容的提问来源于stack exchange,提问作者ashok poudel

