hdr-bubble01 hdr-bubble02 hdr-bubble03 hdr-bubble04

Redirects using htaccess

February 16, 2010

A quick look at redirects using htaccess.

Today I’m going to show you how to force a www and a non www domain using htaccess.

It’s common knowledge that you can access your site with or without the www. By not forcing one or the other this will penalize your SEO, due to duplicate content. The most common method of doing this is via .htaccess using mod_rewrite.

When I was first learning how to use .htaccess this was one of the simpler methods to find examples of with any search engine. Now, if you are only needing to edit your. htaccess for one domain, the majority of these found examples will suffice; If you have multiple domains that tend to go to one directory this example will be much more beneficial. Also, if you put this example into your httpd.conf file, this can take effect on all domains on the server; so you won’t need to worry about adding each domains redirect.

I have provided the below examples as a method I use to manage redirects. I have provided an example for each method, www and non-www.

In order for mod_rewrite to work you must first enable it. This is easily done by adding this to the .htaccess.

RewriteEngine On
Force www:
# Do a www redirect on the domain
RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]

Force non-www
# Do a non-www redirect on the domain
RewriteCond %{HTTP_HOST} ^www\.[a-z-]+\.[a-z]{2,6} [NC]
RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

How this works:

When the URL is being received we check it to ensure it is valid to our method of choice. Regardless of our method, it checks the URL to see if it matches, checks if the URL contains the www or not. Next it will set the conditional variable to be used in the actual redirect.

InformationCategory & Tags

Enjoy this tutorial?Help us Promote it!

Share this on del.icio.us Digg this! Share this on Facebook Share this on Reddit Share it on StumbleUpon Tweet This!
Jeremy Simkins
  • Jeremy Simkins

  • Jeremy Simkins is an accomplished senior web developer with over nine years in the production field. Experienced PHP developer as well as a passionate software engineer. Jeremy specializes in code optimization, performance, and implementation.
  • Website: http://son9ne.com

No Responses to “Redirects using htaccess”

Leave a Reply

  1. avatar arrow

    Your Name
    February 16th

Back To Top
Keep'n It Locked, Pixil.info
We publish fresh new content regularly!
  • Contents and resources released under Creative Commons License.
  • Copyright © 2010 Pixil.info | Pixil 2010 Theme - All Rights Reserved.

Powered by WordPress, hosted by NullGrip. Icons by KomodoMedia. Design & Code by Noe Ruiz.