Rewrite domain.com to www.domain.com using htaccess in Apache

Contributor Icon Contributed by qmchenry Date Icon December 27, 2003  
Tag Icon Tagged: Apache web server

You may want all visitors to your site using www in front of your domain name (www.yourdomain.com) instead of just your domain name (yourdomain.com). By implementing a simple .htaccess RewriteRule, visitors to yourdomain.com will see the URL change in their browser as they are redirected to the correct URL.


To redirect a URL such as “http://yourdomain.com/images/logo.png” to “http://www.yourdomain.com/images/logo.png” use:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yourdomain\.com
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=permanent,L]

In the RewriteRule code, the R=permanent sets the type of redirection (permanent is 301; the default is temporary or 302). The L makes this the last Rule to use and stops rewrite processing.

Previous recipe | Next recipe |
 
  • Thanks i will try
  • Why? WWW (World Wide Web) was incorporated to force browsers to use the HTTP protocol when the Internet was new. Now all modern browsers default to HTTP by default, so what is the point of WWW? Mail servers certainly don't require you to use 'address@mail.yourdomain.com', so why should the web be any different?

    No, sites should be redirecting the 'www' subdomain to the TLD without 'www'. See http://no-www.org for more info. Class B compliance should be the goal of every site owner. Forcing WWW is just silly and redundant.
blog comments powered by Disqus