Swissdude Swissdude - 28 days ago 7
Apache Configuration Question

htaccess rewrite-rule creates endless loop

I have this:

RewriteCond %{HTTP_HOST} ^(www\.)?my-site\.com [NC]
RewriteCond %{REQUEST_URI} !^/sub-dir(/)?$ [NC]
RewriteRule ^(.*)$ /sub-dir/ [R=301,L]


The rule is supposed to mean:

If someone goes to www.my-site.com and DOESN'T add /sub-dir, redirect them to www.my-site.com/sub-dir/

The first step works. Means, when entering www.my-site.com/ I get redirected to www.my-site.com/sub-dir/

But then an endless loop occurs and the redirect doesn't stop.

What am I doing wrong?

Answer Source

Use THE_REQUEST variable instead of REQUEST_URI

RewriteCond %{HTTP_HOST} ^(www\.)?my-site\.com [NC]
RewriteCond %{THE_REQUEST} !\s/+sub-dir[/?\s] [NC]
RewriteRule ^ /sub-dir/ [R=301,L]

Due to other rules below this rule REQUEST_URI is changing to something else (maybe index.php) and causing this negative RewriteCond to succeed again.

THE_REQUEST on the other hand, doesn't change after application of other rewrite rules.