HOWTO: Redirect all non-www pages to their www counterparts using mod_rewrite

Prerequisites

Remember to backup any files first before modifying them, and if possible test changes on a non-production server first

Step 1: Create .htaccess file

If it doesn't already exist, create a file on your server's document root (the top most web accessible directory) and name it .htaccess.

Note to windows users: Windows makes it difficult to save files begging with a period, to bypass this issue name the .htaccess file something else while editing locally, and rename on the server.

Step 2: Add rewrite code to .htaccess file

Add the following lines to the the .htaccess file:
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteBase /
	RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com [NC]
	RewriteRule ^(.*) http://www.mywebsite.com/$1 [L,R=301]
</IfModule>

Replace www\.mywebsite\.com with your own website, remembering to escape any periods with a backslash. Then, also replace http://www.mywebsite.com/ with your own site's address. That's it.


Comments


Submit Comment






More URL Rewriting Articles

None found