Categories
Code Web Work

.htaccess forcing www in urls

I’m starting to use this site as a resource for myself, because I use this stuff all the time, but not enough to commit it fully to memory.

That said, something that’s come up a lot recently is forcing www. in front of all urls on a site. Since all of my servers are Apache, with mod_rewrite enabled, this is no problem. Create an .htaccess file and drop this code into it:

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

The other thing I’ve started doing is using 301 redirects when launching a new site. I can’t believe I didn’t use this years ago! Just add the following to the .htaccess file:

redirect 301 /oldpage.htm http://www.chrisrunnells.com/

And voila, the server redirects the user, and the search engines index the new page as the old one.