]> Forwarding non-www requests to www domain | Web Developer Reference Blog

Forwarding non-www requests to www domain

Add this snippet to your .htaccess file to automatically and visibly rewrite the URL entered by the user, to a single URL. i.e. ‘www.example.com/somepage/’ and  ‘example.com/somepage/’ should both resolve to ‘www.example.com/somepage/’.

The .htaccess file should be located in the root of your website and created in a unformatted text editor such as notepad. If you are running a windows operating system, you will be prevented from creating a file without a file extention. You will need to rename the file once uploaded.

Add the following to your .htaccess file:

###################################################
# Turn the RewriteEngine on.                      #
#                                                 #
# Ensure you add these rules to the top of your   #
# .htaccess file                                  #
###################################################
 
RewriteEngine on
 
###################################################
# Add a leading www to domain if one is missing.  #
###################################################
 
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Tags: .htaccess, Apache, Server Administration, Web Servers

Leave a Reply