Basic HTTP Authentication in Drupal Site Using settings.php
Here’s a quick and painless way of preventing public access to a Drupal site using settings.php (or settings.local.php).
I’ve been using this for development and staging sites that I want to keep private.
If you want this to be available to all settings*.php files you should put this near the top of your settings.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** * Locks the site via basic http auth. * * D7: if (!drupal_is_cli()) * D8: if (PHP_SAPI !== 'cli') * * @param array $users * Array of users e.g., ['user1' => 'pass1', 'user2' => 'pass2']. * * @see https://agileadam.com/2018/04/basic-http-auth-drupal-site-using-settings-php/ */ function lock_with_basicauth($users) { if (PHP_SAPI !== 'cli') { $valid_users = $users; $valid_usernames = array_keys($valid_users); $user = (!empty($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER'] : ''; $pass = (!empty($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW'] : ''; if (!((in_array($user, $valid_usernames)) && ($pass == $valid_users[$user]))) { header('WWW-Authenticate: Basic realm="Private Site"'); header('HTTP/1.0 401 Unauthorized'); die('Not authorized.'); } } } |
Then, you can leverage it wherever you’d like. For example, on an Acquia site I might add this to the bottom of settings.php:
1 2 3 4 5 6 7 8 9 10 |
if (!empty($_ENV['AH_SITE_ENVIRONMENT'])) { switch ($_ENV['AH_SITE_ENVIRONMENT']) { case 'dev': lock_with_basicauth(['agileadam' => 'mysecretdevpass']); break; case 'test': lock_with_basicauth(['agileadam' => 'mysecretstagepass']); break; } } |
For non-Acquia sites I’d call the function at the bottom of settings.local.php.