Nginx拦截特定国家请求:Amazon API Gateway场景X-Forwarded-For处理
Great question! When traffic routes through Amazon API Gateway, your Nginx server sees the API Gateway's IP address in $remote_addr instead of the end user's real IP. That’s why your existing geoip setup isn’t working—you need to tell Nginx to use the IP from the X-Forwarded-For header (which API Gateway sets with the original client IP) for country lookup.
Here’s how to adjust your configuration to make this work:
Step 1: Extract the Real Client IP from X-Forwarded-For
API Gateway appends its own IP to the end of the X-Forwarded-For header, so we need to capture the first IP in that header (this is the end user’s real IP). Add this map to your nginx.conf:
# Extract the first IP from X-Forwarded-For; fall back to $remote_addr if the header is missing map $http_x_forwarded_for $real_client_ip { default $remote_addr; ~^(?P<first_ip>\d+\.\d+\.\d+\.\d+) $first_ip; }
Step 2: Configure GeoIP to Use the Real Client IP
By default, the ngx_http_geoip_module uses $remote_addr for IP lookup. Update your geoip configuration to use our extracted $real_client_ip instead:
# Tell geoip module to use the real client IP for country/city lookup geoip_from $real_client_ip; # Load your existing geoip databases geoip_country /etc/nginx/GeoIP.dat; geoip_city /etc/nginx/GeoLiteCity.dat; # Your country allowlist map remains unchanged map $geoip_country_code $allow_country { default yes; US no; }
Step 3: Keep Your Blocking Logic in Place
Your existing rule in domain.conf can stay as-is—it will now use the country code derived from the real client IP:
if ($allow_country = no) { return 444; # Close the connection without sending a response }
Important Security Note
To prevent attackers from forging the X-Forwarded-For header, ensure your Nginx server only accepts traffic from Amazon API Gateway’s official IP ranges. You can add these allow rules to your domain.conf:
# Allow only Amazon API Gateway IPs (update these ranges with the latest from AWS docs) allow 3.5.140.0/23; allow 18.208.0.0/13; allow 52.46.0.0/15; deny all;
After updating your configuration, reload Nginx with sudo nginx -s reload to apply the changes. This setup will correctly identify the end user’s country even when traffic comes through API Gateway, and block requests from the US as intended.
内容的提问来源于stack exchange,提问作者Sathish Kumar

