How to redirect non-www domain to www domain in .htaccess?
Posted on In QAI have a website. But I would like use the www.example.com instead of example.com.
How to redirect non-www domain to www domain on my server? I am using apache2 (httpd).
You can add a piece of code into the top .htaccess in your site:
Table of Contents
Specific method: redirect example.com domain to www.example.com domain
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
General method: redirect non-www domains to www domains
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Bonus:
Redirect www domains to non-www domains
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]