'RewriteRule in folder breaks parent (.htaccess)

# /.htaccess
RewriteEngine on
RewriteBase /
RewriteRule "^([^/]+)/root/(.*)"   "$1/index.php?root=$2"

# /folder/.htaccess
RewriteRule "^sub/(.*)"            "index.php?sub=$1"

Each folder's RewriteRule works in isolation:

  • /folder/root/hi => /folder/index.php?root=hi
  • /folder/sub/hello => /folder/index.php?sub=hello

Q: Why does adding any RewriteRule in the subfolder (/folder/.htacces) break the one in the web root (causes 404)? What do I need to do to create rules on different levels?

I've tried adding RewriteOptions Inherit(Down), but that didn't have any effect.



Solution 1:[1]

You need to change your root .htaccess rule to this:

RewriteRule ^([^/]+/)?root/(.*)$ $1index.php?root=$2 [L,QSA]

This is to make initial part [^/]+/ an optional match in order to make same rule work from root .htaccess as well as from a /folder/.htaccess.

Then have this in your folder/.htaccess:

RewriteOptions Inherit
RewriteEngine On

RewriteRule ^sub/(.*)$ index.php?sub=$1 [L,QSA]

RewriteOptions Inherit will inherit all rules and directives from parent .htaccess and will apply them in child's context after applying all the rules defined in child .htaccess.

Solution 2:[2]

With Apache 2.4, I've success by adding RewriteOptions InheritDownBefore in the parent .htaccess.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anubhava
Solution 2 GiDo