How to redirect non-www domain to www domain in .htaccess?

I 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:

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]
Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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