What does the following mod_rewrite code do?
I was wondering what does the following mod_rewrite code do,开发者_开发技巧 can someone explain the code in detail?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]
Line by line interpretation:
RewriteRule .* index.php [L]
Will be interpreted first and match every request (matched against the part of the URL after the hostname and port, and before the query string). .*
is a regular expression to match all the time. A better and faster rule might be:
RewriteRule ^ index.php [L]
^
in regex means, match every string that has a beginning. This is equal to .*
-> match every thing.
After a match was found, the processing will continue with the RewriteCond
(itions).
The two RewriteConditions are chained by a invisible logic AND
. This block will only match if both RewriteConditions are true.
RewriteCond %{REQUEST_FILENAME} !-f # Check if given file is not a file AND
RewriteCond %{REQUEST_FILENAME} !-d # Check if given directory is not a file and
Example: If you'll have the following file structure on the server.
.
|-- css
| `-- base.css
|-- img
| `-- logo.png
`-- index.php
If you request the URL example.com/css/base.css the following steps will happen.
- Match for RewriteRule (match all the time)
- Won't match
RewriteCond %{REQUEST_FILENAME} !-f
, becausecss/base.css
is a file. RewriteRule
will be skipped because no match occurred, processing will test other rules and conditions*
If you request the URL example.com/en/about the following steps will happen.
- Match for
RewriteRule
(match all the time) - Match
RewriteCond %{REQUEST_FILENAME} !-f
, becauseen/about
is no file. - Match
RewriteCond %{REQUEST_FILENAME} !-d
, becauseen/about
is no directory. - Combination of
RewriteRule
andRewriteCond
created a positive match -> - Redirect the request to
index.php
with the flagL
The flag L
means last rule, which will stop the processing. More on flags.
This rule combination is often used to redirect all request to an single entry point of an web application. To avoid serving static content by index.php
, files and directories will be served by web server and not by the index.php. The dispatching of the dynamic site request will be done inside the logic of index.php
.
* The correct data flow can be found here
It rewrites all requests which does not match a file ((!-f)
) or directory((!-d)
) on disk to index.php. [L]
tells mod_rewrite to stop processing rules after this one.
精彩评论