Redirect Drupal to non-www via settings.php

When you update Drupal core, the .htaccess file is overwritten with the latest version. This also means that any www redirects in that file are lost, and you have to re-apply them, which is annoying, and a problem if you forget to do it after updating. The reason why it is important to only show URLs with OR without www. in front of them, is to avoid what Google considers duplicate content.

In stead of redirecting via .htaccess, you can also do it via settings.php, which will not change after core updates. Put this in your settings.php. It will also work for sub-pages, like

// Remove www
if ($_SERVER['HTTP_HOST'] == '') {
header('HTTP/1.0 301 Moved Permanently');
header('Location:'. $_SERVER['REQUEST_URI']);

Solution found at Pantheon:

Redirect via Apache

You can also define the redirect in your Apache server, in a file called for example /etc/apache2/sites-enabled/ This might be preferable, since it happens earlier in the process, but requires access to the apache server. Note that everything after com/ will be carried over to the redirected page, so becomes Insert this at the very top of the file, before the rest of the virtualhost configuration:

# redirect www to non-www
<VirtualHost *:80>
  Redirect permanent /
<VirtualHost *:80>

If you want it the other way around, just swap the www.

Solution found here: