Non-www URLs can be redirected to www URLs using the .htaccess file.
To re-write the website URL from non-www to www the .htaccess file is edited and the rewrite rules added.
The Apache mod-rewrite module will be used to perform the rewriting of the website URL.
The RewriteEngine is turned on and then conditions are set for the rule. First to determine whether we are covering http or https.
A rule is created for the test, based upon regular expressions to ensure that the website URL is a is missing its starting www. ^www signifies starting with www and the exclamation mark inverts the condition.
The results from the test are then used to implement the change to a www URL. The URL is taken as the first parameter, later referenced as $1. A redirect of error code 301 (moved permanently) is specified.
HTTP_HOST is the target host sent by the client.
Below the rewrite rules for non-www to www and the opposite www to non-www are given. In each instance both http and https are covered.
Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Redirect www to non-www
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
The .htaccess file is used to provide access control on a per directory basis. It allows for the configuration based upon the Apache options, but by the website developer rather than the server administrator.
A .htaccess file may be placed within each directory. There is usually one in the root of the website. the security for the .htaccess file should be set to 644. This can usually be set using the FTP package.


