So there comes a time and a place where you want foo.com to redirect to www.foo.com for design, clarity, seo, and possibly other reasons, and doing so can seem tricky. Well I’m here to let you know, it is not. Using some simple mod_rewrite coding, it can be done quickly and effectively.

First things first, make sure you have mod_rewrite enabled on your server. If you don’t, you’re pretty crazy.

Next, either create or edit your .htaccess file in your webroot directory, which tends to be public_html, www, or httpdocs.

Drop in the following lines of code:

RewriteEngine on
#HTTP REDIRECT
RewriteCond %{HTTP_HOST} ^foo\.tld$ [NC]
RewriteRule ^(.*)$ http://www.foo.tld/$1 [R=301,L]
#END REDIRECT

Replace foo with your domain name, i.e. theubersexualman
Replace tld with your domain extension, i.e. com

So you should end up with code resembling this:

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

Save your .htaccess file and test it out.  You should not need to restart or reload apache for this to work.

This however, will not take care of https, so if you are running a secure site and non secure site with the same directory housing, you’ll want to use this code:

#HTTPS REDIRECT
RewriteCond %{SERVER_PORT} ^443$
RewriteCond %{HTTP_HOST} ^foo\.tld$ [NC]
RewriteRule ^(.*)$ https://www.foo.tld/$1 [R=301,L]
#HTTP REDIRECT
RewriteCond %{HTTP_HOST} ^foo\.tld$ [NC]
RewriteRule ^(.*)$ http://www.foo.tld/$1 [R=301,L]
#END REDIRECTS

And again, replacing foo and tld respectively .

Posted by Drwndx, filed under Geek |
Date: July 15, 2008, 12:02 pm |

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.