RewriteCond REQUEST_URI not match whole path

1.2k Views Asked by At

I am quite puzzled.

My goal is to detect, whether redirect is needed (path changed). This is a minimal example.

RewriteRule ^first$ second

RewriteCond %{REQUEST_URI} !^/$1$
RewriteRule ^(.*)$ /$1 [R=301,L]

And I am requesting example.com/first with intention to get 301 to second.

Problem is, that the RewriteCond always evaluates to true and creates a loop. On the first go, it is fine. But on the second request, which is now example.com/second, it evaluates to true again, even though %{REQUEST_URI} is /second and $1 is second. I know it is.. I checked by redirecting to URL with both variables appended.

Any idea what am I missing?

1

There are 1 best solutions below

3
On BEST ANSWER

Please remember 2 important facts here:

  1. mod_rewrite rules are run in a loop and it stops only when there is no successful rule execution
  2. Value of %{REQUEST_URI} changes after rewrite or redirect.

Looking at your rules your 2nd redirect rule is faulty since you cannot use %1 or $1 in value part of RewriteCond thus making it always return true due to negation.