1

I want everything to be redirected to index.php, so I thought this should work:

RewriteEngine on
RewriteRule ^(.*)$ /index.php?url=$1 [L]

..but it doesn't. This very similar RewriteRule does work though:

RewriteEngine on
RewriteRule matches/(.*) /index.php?url=$1 [L]

I later found out that to make the first one work you need:

RewriteCond %{REQUEST_FILENAME} !-f

Can someone please explain why the last RewriteCond is needed in the former example but not the latter?

Akuta
  • 3,290
  • 2
  • 15
  • 9

1 Answers1

3

Because first rule will rewrite already rewritten URL.

RewriteRule Last [L] flag not working?

For example:

  • Original request: /hello/pink-kitten
  • 1st (initial) rewrite: /index.php?url=hello/pink-kitten
  • 2nd cycle: rewritten to /index.php?url=index.php
  • 3rd cycle: rewritten to /index.php?url=index.php
  • No more cycles, as 3rd cycle produced the same result as 2nd

Why rule works if added that condition? Because the condition clearly says -- only do rewrite if requested URL is not file. Therefore, on 2nd cycle URL will not be rewritten again as /index.php is a file, therefore no more cycles.

Why 2nd rule works just like that? Because it already has condition built in -- URL should contain matches/ in it, and rewritten URL /index.php?url= as you can see has no matches/ part in it.

Community
  • 1
  • 1
LazyOne
  • 158,824
  • 45
  • 388
  • 391
  • One question then, which one would be correct to serve everything to index.php: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule (.*) /index.php?url=$1 or RewriteCond %{REQUEST_URI} !^index.php RewriteRule (.*) /index.php?url=$1 – Akuta Apr 27 '12 at 04:48
  • First one -- it will process requests to NOT existing files only, so css/js/images/etc will be served by web server as usual. 2nd one (BTW, it will not work, as condition is a bit wrong) will rewrite EVERYTHING to the index.php, even existing static files. – LazyOne Apr 27 '12 at 08:46