Get the client IP address when using the CDN#
As you can see in the CDN architecture, there are a number of layers between the end user and your application.
To get the actual client IP address, you will need some tweaks in your application.
The latest IP ranges of the CDN are always available in the Fastly API.
Drupal specific instructions#
See the documentation for Drupal.
Nginx#
Nginx by default will log the first external IP address that is seen. You can alter this to be the client IP. This only really impacts the logs, or if you are doing IP address filtering in Nginx.
environments:
main:
routes:
- nginx:
- "www.example.com":
tls-acme: 'true'
annotations:
nginx.ingress.kubernetes.io/server-snippet: |
set_real_ip_from 23.235.32.0/20;
set_real_ip_from 43.249.72.0/22;
set_real_ip_from 103.244.50.0/24;
set_real_ip_from 103.245.222.0/23;
set_real_ip_from 103.245.224.0/24;
set_real_ip_from 104.156.80.0/20;
set_real_ip_from 140.248.64.0/18;
set_real_ip_from 140.248.128.0/17;
set_real_ip_from 146.75.0.0/17;
set_real_ip_from 151.101.0.0/16;
set_real_ip_from 157.52.64.0/18;
set_real_ip_from 167.82.0.0/17;
set_real_ip_from 167.82.128.0/20;
set_real_ip_from 167.82.160.0/20;
set_real_ip_from 167.82.224.0/20;
set_real_ip_from 172.111.64.0/18;
set_real_ip_from 185.31.16.0/22;
set_real_ip_from 199.27.72.0/21;
set_real_ip_from 199.232.0.0/16;
set_real_ip_from 2a04:4e40::/32;
set_real_ip_from 2a04:4e42::/32;
Laravel#
Your Laravel application’s TrustProxies middleware file lives at app/Http/Middleware/TrustProxies.php. This middleware tells Laravel which proxy IP addresses it should trust and what headers to accept that determine the client's true IP address.
The TrustProxies middleware has two key properties you need to know about:
$proxies: Lists your trusted proxy IP addresses
$headers: Defines your trusted forwarded headers
This blog post has a good explanation of how to configure your Laravel application to trust the CDN IP addresses.
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Support\Facades\Config;
use Symfony\Component\HttpFoundation\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
* Use '*' to trust all proxies or specify individual IPs.
*
* @var array|string|null
*/
protected $proxies = [
'23.235.32.0/20',
'43.249.72.0/22',
'103.244.50.0/24',
'103.245.222.0/23',
'103.245.224.0/24',
'104.156.80.0/20',
'140.248.64.0/18',
'140.248.128.0/17',
'146.75.0.0/17',
'151.101.0.0/16',
'157.52.64.0/18',
'167.82.0.0/17',
'167.82.128.0/20',
'167.82.160.0/20',
'167.82.224.0/20',
'172.111.64.0/18',
'185.31.16.0/22',
'199.27.72.0/21',
'199.232.0.0/16',
'2a04:4e40::/32',
'2a04:4e42::/32'
];
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO;
}