301 Redirect from domain.com to www.domain.com

Last modified: August 23, 2009 - 22:36

NOTE: using .htaccess rules is a much better way to accomplish this goal.

I needed to use 301 to redirect all non-www requests for a site to the www version and here's how I did it. I made two folders in the sites folder:

sites/www.domain.com/settings.php
sites/domain.com/settings.php

I then put the following in the non-www (domain.com) settings.php file. This is the entire contents of the file:

<?php
  $host
= $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'];
 
$request = $GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'];
 
header("HTTP/1.0 301 Moved Permanently");
 
header("Location: http://www.$host$request");
 
header("Connection: close");
?>

I would rather do this with mod_rewrite, but it looks complex and I don't have time to study that right now. If anybody has a suggestion that would work in a multisite environment, that'd be really great.

How do it using .htaccess

Matt G - November 6, 2009 - 15:57

I'm sure this is somewhere else on Drupal.org, but I figured I'd post this here.

The better way to do this is to edit your .htaccess file, which should be located in your root directory on your web server.

It's usually a hidden file, so if you're using CPanel you have to select the option to "show hidden files (dotfiles)" to be able to see it.

Once it's open, scroll down to this section:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # adapt and uncomment the following:
  RewriteCond %{HTTP_HOST} ^YOURDOMAIN\.com$ [NC]
  RewriteRule ^(.*)$ http://www.YOURDOMAIN.com/$1 [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment and adapt the following:
  # RewriteCond %{HTTP_HOST} ^www\.YOURDOMAIN\.com$ [NC]
  # RewriteRule ^(.*)$ http://YOURDOMAIN.com/$1 [L,R=301]

If you want to rewrite from domain.com to www.domain.com, un-comment out the first section:

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

I had to do this to get the Secure Pages module to work properly: it worked great if users went to www.mysite.com, but not at all if they went to mysite.com.

This redirects every user to www.mysite.com

 
 

Drupal is a registered trademark of Dries Buytaert.