Force non-www to www in htaccess

Posted 3 years ago

Forcing either non-www to www or vice versa is crucial when it comes to SEO. Being able to access the same page with www or non-www is duplicate content when it comes to the eyes of search engines.

Navigate to your root directory I’ll use the below as an example

/var/www/vhost/domain/htdocs/

Create a file with the name “.htaccess” - note: the dot is intentional

/var/www/vhost/domain/htdocs/.htaccess

Within that file, place the following text


## Force non-www urls to www 
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

You don’t need to restart any services as the .htaccess file is checked every call.

Still experiencing problems

If you’re still having problems you may not have installed mod_rewrite.

Log into your server and run the following command

sudo a2enmod rewrite

Edit your .conf file - note: your name

may

be different

vi /etc/apache2/sites-available/default.conf

There should be a section which looks like this


        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

You want to change AllowOverride None

AllowOverride All

Restart apache and you should be good to go.

/etc/init.d/apache2 restart

If you don’t have access to SSH on your server, contact your host provider who should be able to assist.