Trusted Host Patterns Limit: Site Works Locally but Fails in Production When Host Header Differs
0 reputation · 21 Jun 2020, 12:23 UTC
0 reputation · 21 Jun 2020, 12:23 UTC
When developing a Drupal site locally, the trusted host validation is often bypassed, allowing the site to load without explicit entries in $settings['trusted_host_patterns']. In production, however, Drupal enforces the pattern list, and any request whose Host header does not match an allowed pattern results in a 403/503 response. This discrepancy becomes pronounced when the production environment sits behind a load balancer or SSL terminator that may alter or forward the Host header, requiring the pattern list to include the exact hostname seen by Drupal.
The goal is to define a trusted_host_patterns configuration that satisfies both the permissive local development environment and the strict production requirements without compromising security or requiring frequent manual updates.
What pattern array should be used when the site is accessed via a load balancer that preserves the original Host header? Should separate settings.php files be maintained for each environment, or can a single array safely contain both localhost and production hostnames? Is it acceptable to rely on the default permissive behavior for local development, or must explicit patterns be added to avoid unexpected failures when the code is promoted?
35275 reputation · 21 Jun 2020, 17:20 UTC
trusted_host_patterns array in settings.php that matches the exact Host headers received by the Drupal application.The failure occurs because Drupal's trusted host validation is disabled when the configuration is empty, which is common in local environments. In production, once patterns are defined, Drupal strictly enforces them. If your load balancer or SSL terminator forwards a Host header that does not match your defined patterns, Drupal returns a 403 Forbidden or 503 error.
You can use a single settings.php file by using environment detection to conditionally add patterns. This avoids maintaining separate files across environments while ensuring strict security in production.
// In settings.php
$settings['trusted_host_patterns'] = [
'^localhost$',
'^127\.0\.0\.1$',
];
// Add production patterns conditionally based on an environment variable
if (getenv('DRUPAL_ENV') === 'production') {
$settings['trusted_host_patterns'][] = [
'^yourdomain\.com$',
'^www\\.yourdomain\.com$',
];
}
\.) and use anchors (^ and $) to prevent unintended partial matches.If the site still fails after adding patterns, is your load balancer configured to pass the Host header through, or is it using a custom X-Forwarded-Host header instead?
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.