Where to use setTrustedProxies() or how to set new trusted proxies
-
30-01-2021 - |
سؤال
I need to set a trusted proxy in my installation so that secure cookie flags are set correctly.
Currently as a temporary measure i am setting the following in index.php
$proxies = ['122.128.0.1'];
Request::setTrustedProxies($proxies);
However i would like to be able to set a new trusted proxy from a settings file or module that will persist through a core update without needed to patch.
Where is the best place to specify this?
المحلول
Drupal doesn't want you to place custom code in index.php to prepare a request before it is handled by the Drupal kernel. So it was made possible for modules to implement a middleware through StackedHttpKernel.
In this case such a middleware already exists, which reads the reverse proxy addresses from settings.php and adds them as trusted proxies to the request:
Drupal\Core\StackMiddleware\ReverseProxyMiddleware::setSettingsOnRequest:
$proxies = $settings->get('reverse_proxy_addresses', []);
if (count($proxies) > 0) {
$request::setTrustedProxies($proxies, Request::HEADER_X_FORWARDED_ALL | Request::HEADER_FORWARDED);
So you can simply enable this settings in settings.php:
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['a.b.c.d', ...];
نصائح أخرى
All the other proxy settings are in settings.php
so I think that would be the most appropriate place.
This would persist after core updates and as a new developer on boarding onto a project that is the first place I would check for this sort of configuration.