How to remove www prefix from domain with mod rewrite for drupal and cakePHP

It is a bad idea to leave multiple domain names serving the same content as web crawlers will lower your rankings.

To get better SEO positioning you should rewrite url to make them point to the same url with 301 permanent redirects.

How to rewrite urls to remove www prefix

You need to create .htaccess file or edit existing one and add a section:

   RewriteEngine On
   RewriteCond %{HTTP_HOST} !^artur\.ejsmont\.org$ [NC]
   RewriteRule ^(.*)$ http://artur.ejsmont.org/$1 [R=301,L]

It will redirect (302 permanent client redirect) from all domain names different than artur.ejsmont.org in this case.

You also need to make sure apache has mod_rewrite enabled:

apachectl -M

If you do not have the module you need to enable it or recompile if your distribution does not ship it.

On debian just add link to enabled-modules in /etc/apache2

Last step is to make sure apache allows owerwriting of config. Look out for httpd.conf with directive like this.

AllowOverride none

In such case .htaccess files would be ignored.

Ps. great thing about htaccess files is they do not need apache server restart.

Comments

You can also create canonical

You can also create canonical urls without www using PHP, but .htaccess is way more efficient.

<?php
if(!strstr($_SERVER['HTTP_HOST'],'www.'))
return;
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://'.substr($_SERVER['HTTP_HOST'],4).$_SERVER['REQUEST_URI']);
exit();
?

2011-01-08 19:28

Post new comment

Image CAPTCHA