Yaron U.
Yaron U.

Reputation: 7891

www RewriteRule not applying to subdirectories with other RewriteRules

I have an .htaccess file in my root folder to redirect non-www accesses to www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule .* https://www.example.com/$0 [L,R=301]

The rule works fine, but in a subdirectory (call it /sub) where I have another .htaccess file with rewrite rules - the www rule is not applied.

Of course I can copy paste it - but that is obviously not the best solution.

I've tries adding RewriteOptions Inherit to the subdirectory's .htacces - and the rule works, but the rules works in relation to the sub folder and not the sub folder so http://example.com/sub/something.html is redirected to https://www.example.com/something.html (removing the sub folder from the path)

Setting RewriteBase / in the subdirectory's htaccess isn't good as well - since it interferes the other rules I have in the file

I'd really appreciate your help

Upvotes: 0

Views: 151

Answers (1)

anubhava
anubhava

Reputation: 785541

By default sub directory's .htaccess doesn't inherit rules defined in parent .htaccess. To enforce this behavior you need to insert this line in /sub/.htaccess:

RewriteOptions Inherit

before RewriteEngine On line.

Read more about RewriteOptions

Though keep in mind that parent .htaccess rules are only applied after your current .htaccess rules and there is no way to change this behavior in Apache 2.2 at least. If this is affecting you then you will need to copy www rule and place it above your other rules in /sub/.htaccess.

EDIT: Also change your root https rule to this:

RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301,NE]

Upvotes: 1

Related Questions