Redirecting the Homepage using mod_rewrite

How to redirect a homepage from example.com to www.example.com using mod_rewrite.

Redirect the Homepage? Huh? Why?

This is Spring, 2005 and for a while some people, myself included, have experienced some difficulty with the way some search engines have been handling the issue of a site homepage with or without the www. Technically, www. is a sub-domain rather than the actual root directory of the website, in the same way that shopping.example.com is.

There may be some links to the site, both from external inbound links and within the site itself in the internal navigation, as example.com and some as www.example.com - which can very possibly split up the count of inbound links to the site, and can also *maybe* result in there being indication of duplicate content, since technically example.com and www.example.com are actually two different pages.

Remember that there are two types of redirects:

  • Permanent redirection: 301 Redirect
  • Temporary redirection: 302 Redirect:

Redirect non-www to www.

What you want for redirecting your homepage is a permanent redirect, not temporary. And as long as your server supports mod_rewrite, it's a simple matter to copy and paste a couple of lines of simple code into the .htaccess file, which goes like this:

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

Redirect www. to non-www.

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

Redirect requests for domain with index.html to www.

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.html\ HTTP/
RewriteRule ^index\.html$ http://www.example.com/ [R=301,L]

Redirect Dedicated IP Number to http://www.example.com

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

Make sure to change the URL to your own domain name. Yes, I have redirected pages to www.example.com - it's easily fixed in a few seconds.

That will redirect any requests for example.com to www.example.com Try it by clicking on http://webmasterwoman.com and you'll see that you're seamlessly redirected.

This is simple, it works, and it's one of the best things you can do to make sure all your pages are properly indexed and links and site navigation are properly figured when the site is crawled or navigated.


Redirection Using Mod_Rewrite | Redirecting the Homepage
Redirecting Web Pages using mod_alias | Creating an .htaccess file
File Sizes | Web Safe Colors

spacer_468x60