.htaccess Redirect from Non-WWW to WWW

Last Updated on: January 28, 2023

If you can access your website both with www and without then you are effectively serving duplicate content. I am sure Google are sensible enough to filter this out but some people feel like it could be an issue so my recommendation is better safe than sorry.

Place the following code in your .htaccess file to automatically force www. on the front of your URLs:

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

You might not need the “RewriteEngine On” – check if it already exists in your .htaccess

There are a lot of other solutions using .htaccess. Still, this particular solution does not need editing (i.e. your URL is not in the code), so you can use it in a distributed project or many websites without having to customise it.

Get notified of new posts:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *