How do I redirect to www and https in settings.php? I want to include code in settings.php which would handle redirects to the www alias and also https. 

Because it is for a distribution I would prefer not to have hard-coded URLs and I would also prefer not to be changing the .htaccess file so that core updates are easier.

I am using the code below, and I just want to be sure it doesn't have any security issues. Does it have any security issues, and I should therefore use different code?

// Redirect to www
  if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
exit;
}
// Redirect to HTTPS
  if($_SERVER["HTTPS"] != "on")
{
  header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}
The caveat to the settings.php approach is 2 issues:


Your redirect requires that Drupal be bootstrapped to work. If there's a resource that bypasses Drupal (e.g. any hosted files), you're not going to see the www redirect occur.
It's arguably bad practice. settings.php is for Drupal settings; depending on your intent this might be considered a web server setting. A developer working on your project in a local environment might have trouble understanding where the redirect is coming from as standard Drupal configurations use the .htaccess file for this.


An alternative to prevent .htaccess overwriting would to be place the rewrite directive in an Apache configuration (e.g. vhost.conf if you're using virtual hosts) that defines your host.