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).

asked Oct 9, 2016 by anonymous

1 Answer

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 Oct 9, 2016 by Eric Z Ma (44,280 points)
edited Oct 9, 2016 by Eric Z Ma

Please log in or register to answer this question.

Related questions

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...