Incorrect domain from url and session generator behind reverse proxy

Created on 23 January 2014, almost 11 years ago
Updated 21 August 2023, over 1 year ago

When placing a Drupal 8 site behind a reverse proxy then the URL and session generator ignore the X-Forwarded-Host request header.

Url generator
Absolute URLs are being generated based upon the Host header instead of the X-Forwarded-Host header even when the settings.php is configured to allow reverse proxies. Invoking Drupal::request()->getHost() results in the correct host. The problem is caused by the url generator service being initialized before the ReverseProxySubscriber has a chance to assign trusted reverse proxies.

Session generator
Retrieving session cookie parameters from session_get_cookie_params() results in the domain matching the Host header instead of X-Forwarded-Host.

Proposed fix
This solution moves the trusted proxy logic from ReverseProxySubscriber to drupal_handle_request()

// Create a request object from the HttpFoundation.
$request = Request::createFromGlobals();
// Get the current settings.
$settings = \Drupal\Component\Utility\Settings::getSingleton();
// Check whether the reverse proxy settings should be used.
if ($settings->get('reverse_proxy', 0)) {
  // Allow the request to use the reverse proxy headers.
  $reverse_proxy_header = $settings->get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
  $request::setTrustedHeaderName($request::HEADER_CLIENT_IP, $reverse_proxy_header);
  $reverse_proxy_addresses = $settings->get('reverse_proxy_addresses', array());
  $request::setTrustedProxies($reverse_proxy_addresses);
  // Set the session cookie domain to the correct host.
  ini_set('session.cookie_domain', ".{$request->getHost()}");
}
// Attach the request to the dependency container.
\Drupal::getContainer()->set('request', $request);
🐛 Bug report
Status

Closed: outdated

Version

9.4

Component
Request processing 

Last updated 7 days ago

No maintainer
Created by

🇧🇪Belgium freblasty

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇦🇺Australia thursday_bw

    "I think this ticket should be closed - this issue fixed in the latest Drupal versions." I don't see any evidence or even suggestion of this having been fixed, and since i'm looking at it on Drupal 10 going "this looks exactly like my issue", I am going to re-open it.

    Rather than re-open this ticket, I will mark this related issue, I think they are duplicates: https://www.drupal.org/project/drupal/issues/2998728 🐛 Reverse proxy settings for multisite cannot work Needs work

Production build 0.71.5 2024