Forcing WWW (or Non-WWW) on URLs (via Mod Rewrite)

Posted by: Gremelin

Forcing WWW (or Non-WWW) on URLs (via Mod Rewrite) - 02/01/10 10:42 AM

For whatever reason, you decide that you want to force one set of URLs towards your users, either ProWWW or AntiWWW. Well, with Apache there is a very simple tool to do this, it's called Mod_Rewrite and you can use a .htaccess file to do this.

There are many complicated methods to do this, over the years we've used a good set of them, that is until we found a route to just use one that's triggered for any URL (versus one for every TLD that we own).

First, your .htaccess file must tell the server that "hey, I'd like to use Mod_Rewrite" and then have a set of rules; both of these are:
Code:
RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Line 1 turns mod_rewrite on, lines 3 and 4 tell mod rewrite to look for urls missing the "www" prefix and then rewrite the URL with www attached.

Now, if you'd like to go the other route and force a non-www url on your site you can do this:
Code:
RewriteEngine on

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


This similar rule says that if the www portion of the URL is attached, to strip it away and use just the domain and the uri.

Now some users will argue that "www" is depreciated and shouldn't be used; whereas others would argue that "www" means web, and "ftp" means ftp (etc etc etc), whatever you choose (if wanting to force either) that's up to you.

From an SEO standpoint, I'd say to choose one or the other; some scripts (mainly those which use cookies) will treat both URLs as different sites, so I'd advise you go with one and stick with it.

And yes, we're in the "pro www" camp :P.
Posted by: Gremelin

Re: Forcing WWW (or Non-WWW) on URLs (via Mod Rewrite) - 02/01/10 10:45 AM

In case the above pro-www doesn't work for you, one of the others we've used is:
Code:
RewriteEngine on

rewritecond %{http_host} ^([a-zA-Z0-9]+\.net) [NC]
RewriteRule (.*) http://www.%1/$1 [R=301,L]