Tim Igoe's Web Design, Development and Hosting Blog

Blog > Forcing www. via .htaccess

If, like me, you often set your servers up to allow traffic to your sites from both domain.com and www.domain.com but would rather users only used one, there is a simple way to achieve this with Apache and mod-rewrite.

Putting the following in a file called .htaccess within the root of your website, you can achieve this automatic redirection to www. with little effort and no need for code to perform the check.

.htaccess


RewriteEngine  on

RewriteBase   /

RewriteCond %{HTTP_HOST} !^(www.|$) [NC]
RewriteRule ^ http://www.% {HTTP_HOST}%{REQUEST_URI} [L,R=301]


This code, checks the current HTTP_HOST the user is viewing, so if they were to come via domain.com for an example, it would check to see if the host starts www., this case it doesn't so it would do a 301 redirect to the same URL, but corrected to include www.

Nice and simple, but very useful.

Similar Articles from the web

Forcing www. via .htaccess

Post a reply