Incorrect domain from url and session generator behind reverse proxy

Created on 23 January 2014, over 10 years ago
Updated 21 August 2023, 10 months 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 about 10 hours 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.69.0 2024