Redirecting “http://” to “http://www” using .htaccess
June 24th, 2008When browsing the Internet today we’re accustomed to seeing the good ol’ “http://www” bit on the left side of our URL’s. However, it seems that a growing number of websites have decided that this is not good enough and have created rewrite rules to strip the “www” off of all their addresses, effectively turning http://www.example.com into http://example.com. One of the main culprits of this is our favourite Obama-loving, Microsoft-bashing social ‘news‘ website Digg.
There is next to no benefit to either of these URL formats apart from the size of the URL’s generated. Naturally the smaller one is quicker to write and keeps the address bar focused on the content and not the fact that it’s on the World Wide Web (an obvious fact).
The only benefit that can be achieved from this is to ensure that search engines pick up only one format of your URL’s. From what I can understand having backlinks to http://www.example.com/page.html and http://example.com/page.html will dilute your rankings. To help combat this I have provided some code that will force your website to work with the “www” attached to the URL at all times, even when it is removed.
First of all, create a file named .htaccess (yes, nothing on the left apart from a dot) and add this code with a text-editing program like Notepad. If you have trouble with doing this go to .htaccess Editor and use their free online tool.
RedirectMatch permanent index.html/(.*) http://example.com/$1 RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com%{REQUEST_URI} [R=301,L] RewriteBase / RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.(html|php)\ HTTP/ RewriteRule ^(([^/]+/)*)index\.(html|php)$ http://domain.tld/$1 [R=301,L] RewriteCond %{REQUEST_URI} /+[^\.]+$ RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
Once saved in the .htaccess file upload it to your website in the root (main) directory using an FTP program. Be sure to upload in ASCII format! If you don’t have a FTP program I strongly recommend FireFTP for Firefox users. If you come across any problems and cannot find the .htaccess file to remove then upload a blank one to cancel any changes made with the first.