John Smith
John Smith

Reputation: 1005

RewriteRule showing inconsistence behavior

I have the following rule in my htaccess file (this is the full htaccess file):

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

Using the htaccess tester (http://htaccess.madewithlove.be/) it shows the non-www URL is correctly redirected to a www url (test with mydomain.com/ and mydomain.com/subdirectory/ (goes to www.mydomain.com/subdirectory/).

Now, when I put this htaccess file on my site, it will redirect mydomain.com/subdirectory/ to www.mydomain.com instead of to www.mydomain.com/subdirectory/

Why does it show this inconsistent behavior?

Upvotes: 0

Views: 32

Answers (2)

John Smith
John Smith

Reputation: 1005

So, I looked up what the HTTP_HOST value actually is. It looks like it doesn't contain any further than the domain extension (i.e. domain.com but not anything that's behind that) so it will redirect to domain.com)

I modified the htaccess to the following, which is working:

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

If anyone still has any suggestions how to improve the regex, I'm open for improvements

Upvotes: 0

anubhava
anubhava

Reputation: 785146

You're not using capture value $1 in target:

RewriteEngine on

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

Upvotes: 2

Related Questions