views:

167

answers:

5

I need to redirect any URLs without "www." to URLs with "www." for better search engine optimization. I read that this is possible with mod_rewrite and .htaccess files, but I do not know the right code to use. Can anyone help?

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

There is an excellent example of this in Apache's URL Rewriting Guide.

The following code would redirect any non-www request to a www request:

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

You'd want to put this inside the <Directory> directive of your .htaccess file, or apache config file.

zombat
+6  A: 

Create a file called .htaccess in your root folder (the one where, say, index.html or index.php resides). Put the following into it:

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

To remove www from your url website use this code on .htaccess

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

To force www in your website url use this code on .htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]

Were "YourSite.com" you must replace for your url.

A: 

In addition to using mob_rewrite you can do this with a virtual host directive

<VirtualHost example.com>
   ServerName example.com
   Redirect permanent / http://www.example.com
</VirtualHost>

I usually do it the other way around to remove the extraneous 'www'.

beggs