Redirect Non-www to www URLs but it doesn't work well?

1.4k Views Asked by At

I'm using a .htaccess code that change the url (add 'www.' in non-www urls) but my problem is when entering /subfolder in url , .htaccess redirect doesn't work right.

Example

I enter this url: mydomain.com/demo/ it redirects to: www.mydomain.com (without /demo)
any idea?

Here is my .htaccess code:

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

There are 5 best solutions below

2
On

Maybe this?

# Enforce www
# If you have subdomains, you can add them to
# the list using the "|" (OR) regex operator
RewriteCond %{HTTP_HOST} !^(www|local|admin) [NC]
RewriteRule ^(.*)$ http://www.yourdomainhere.com/$1 [L,R=301]
0
On

Your problem is that, if an .htaccess file is placed in a subfolder of your www root folder, then the name of the subfolder is stripped from the path before it's passed to the rewrite rules:

"When using the rewrite engine in .htaccess files the per-directory prefix (which always is the same for a specific directory) is automatically removed for the RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set. See the RewriteBase directive for more information regarding what prefix will be added back to relative substitutions."

Thus, the ^(.*)$ regex in your rewrite rule, which is supposed to match the entire path and save it in $1, is actually only matching the part of the path after the demo/ prefix.

To fix this, you have two options:

  • a) Move your .htaccess file (or at least this particular rewrite rule) to the www root folder. If you, for some reason, still want it to only match paths under the "demo" folder, replace the ^(.*)$ regex with e.g. ^(demo(/.*)?)$.

  • b) Add the folder name back yourself, making your rewrite rule look something like this:

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

(I also added the NS flag, since you probably want it for "cosmetic" external rewrites like this.)

1
On

I have changed that code and put it in root path, it works well :

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]    
</IfModule>

the .htaccess file should be placed in /demo folder but when I move its location to /demo folder I saw that it can't redirect well.

ie : http://mydomain.com/demo/?querystring redirect => http://www.mydomain.com/?querystring

the problem is that 'demo/' in url is eliminated .

do you have any idea?

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

Try this code for adding www:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI}  [R=301,L,NE]