开发者

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.

  1. Match for RewriteRule (match all the time)
  2. Won't match RewriteCond %{REQUEST_FILENAME} !-f, because css/base.css is a file.
  3. 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.

  1. Match for RewriteRule (match all the time)
  2. Match RewriteCond %{REQUEST_FILENAME} !-f, because en/about is no file.
  3. Match RewriteCond %{REQUEST_FILENAME} !-d, because en/about is no directory.
  4. Combination of RewriteRule and RewriteCond created a positive match ->
  5. Redirect the request to index.php with the flag L

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜