Navnish Bhardwaj
Navnish Bhardwaj

Reputation: 1718

Redirect non-www to www using .htaccess

I access a file on my root like example.com/demo/provider it is redirecting to www.example.com.

How can I correct this so that it will redirect correctly to www.example.com/demo/provider

What I have tried:

Try 1

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

Try 2

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

Try 3

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

I have tried some other codes too, Any suggestions will be appreciated Thanks!

Note: I already searched options available on Stackoverflow. But, none of answer worked for me. So, its not a duplicate question. I respect rules and terms of site.

My .htaccess file is in provider folder. You can take it as sub domain/directory.

Upvotes: 1

Views: 399

Answers (1)

Amit Verma
Amit Verma

Reputation: 41249

If your htaccess is in the /provider folder then you have to use the full path to dir in target url,

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

Or

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

This will correctly redirect your url from :

to

Upvotes: 1

Related Questions