user532493
user532493

Reputation: 345

What do these Two Lines in Mod_Rewrite do?

I've benn trying to figure out what these two lines in Mod_Rewrite do and would appreciate some help. Thanks in advance.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php

Upvotes: 1

Views: 80

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

They check if the requested URI is an existing file or a directory. The ! in front makes the condition "not", thus,, the request does NOT map to a file or directory.

See the -f and -d description in mod_rewrite


Don't all requests map to some file so that it can be loaded by the browser?

No. The request could be for something that doesn't exist and be rewritten. For example, http://en.wikipedia.org/wiki/something would mean the URI is /wiki/something, which doesn't map to any physical file or directory. But internally, there is a rule that rewrites /wiki/something to index.php?title=something, and index.php does exist.


Edit: for edited question

  • The 2 conditions: if the requested URI doesn't map to a file or a directory, apply the following rule.
  • The rule: Take whatever the request is, and append a .php to the end.
  • The logic behind this: mod_rewrite loops until the URI that goes into the rewrite engine and the URI that comes out of it is identical. Without the check to see if the URI maps to a physical file or directory, the rule will loop:
    • URI in = /something
    • Check conditions: /something doesn't exist
    • Apply rule, URI in = /something.php
    • Check conditions: /something.php EXISTS, don't apply rule
    • URI in = URI out = /something.php, stop rewriting
  • Otherwise, without the !-f and !-d checks:
    • URI in = /something
    • Apply rule, URI = /something.php
    • URI in = /something.php
    • Apply rule, URI = /something.php.php
    • URI in = /something.php.php
    • Apply rule, URI = /something.php.php.php
    • loop indefinitely until apache decides to stop and return a 500 error

Upvotes: 4

Related Questions