Some people really don't like the www part in urls. They prefer http://example.com over http://www.example.com. They want www.exampe.com redirected to example.com.
How can we manage this in Drupal? Well, we're going to rewrite urls, so it has to be via a Drupal path or via .htaccess.
We can't use a Drupal path in this case though because Drupal paths come in to play to late in the request flow.
So we have to use .htaccess. Drupal is delivered with a .htaccess file in the root which takes care of all the url writing mumbo jumbo, some url blocking for security etc. We'll have to edit this file.
Oops! We're hacking core. Which is always bad. A better place to add this solution is in you httpd.conf file (apache) or something. But let's assume that for these few lines, you want to adjust core.
Open your root .htaccess file and look for the following lines...
# Various rewrite rules. <IfModule mod_rewrite.c> RewriteEngine on
Change this to the following...
# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*) http://example.com/$1 [L,R=301]
Note that we're using the 301 http code. This says that we're doing a Permanent Redirect. Don't forget to do this!
Comments
Hi Gavin,
This is documented in the .htaccess file in your Drupal root. Just uncomment the section you want.
# 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} ^example\.com$ [NC]
# RewriteRule ^(.*)$ http://www.example.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\.example\.com$ [NC]
# RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
How do I make it the other way around? I want to redirect all http://example.com to www.example.com?
Thanks,
Gavin.
The 301 redirect will make sure Google knows that the pages are actually the same thing.
Post new comment