1

I would like to redirect example.com/test to www.example.com/test and example.com/contact to www.example.com/contact.

So with all the routes of the web. Everything I find, what it does is redirect example.com/test to www.example.com

Below is my code, and with all that I have tried it happens to me the same. They work fine, but they don't do what I want.

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

Please, any suggestions. Thanks!

Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
Silvia
  • 11
  • 1
  • 1
    Possible duplicate of [.htaccess Redirect non-WWW to WWW preserving URI string](http://stackoverflow.com/questions/1685962/htaccess-redirect-non-www-to-www-preserving-uri-string) – Walf Feb 03 '17 at 10:52

5 Answers5

1
//Rewrite to www
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
1

Try below rule,

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
1

Add www prefix to url is easy, please try this

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

Hope this help. And you may want to visit this link to know more https://www.a2hosting.com/kb/developer-corner/apache-web-server/adding-or-removing-the-www-prefix-in-domain-urls

M. K Hossain
  • 807
  • 1
  • 12
  • 28
1

METHOD I

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

METHOD II

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

You can use either of these two. The only difference between two is %{SERVER_NAME} and %{HTTP_HOST}.

Hope it helps!

Wolverine
  • 1,712
  • 1
  • 15
  • 18
0

It seems that you have not searched properly:

http://techstream.org/Web-Development/HTACCESS/WWW-to-Non-WWW-and-Non-WWW-to-WWW-redirect-with-HTACCESS

Wolfack
  • 2,667
  • 1
  • 26
  • 50