How to redirect non-www URLs to www in htaccess?

QuestionsHow to redirect non-www URLs to www in htaccess?
sheen asked 7 years ago

can you help me write an htaccess rule on how to redirect my website and all its urls from non-www to www in htaccess? single domain and the one that automatically detects the domain name.
thank you!

1 Answers
Best Answer
karl answered 7 years ago

for single domain. you can simply use this: (replace example.com with your actual domain name)

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L] 

 
This one below will work on any domain, you don’t have to edit it, just paste it on your .htaccess file:

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