问题
In an htaccess file, is it necessary that the rewrite rules follow an order? Like, long ones first and shorter ones last or something like that? Or, is it ok to put them in any order. I only have a few rules like the ones below (some 20), but it's all a big mess.
RewriteRule ^/?(backend)/(users)/(new|blocked)/([a-z0-9]+)/?$ /blah/users/index.php?type=$2&case=$3&offset=$4 [NC,L]
回答1:
Ordering of rewrite rules is very important in .htaccess
. You need to put most specific ones at the top and the most generic (catch all) type rules in the end.
Let me show it by example. Suppose you want to hide .php
extensions for all valid .php
files but want to forward rest of the files to index.php then you need to write PHP hiding rules first like this:
# first try loading PHP file if available
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L,NC]
# not available then send it to /index.php?file=<file>
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php?file=%{REQUEST_URI}.php [L,QSA]
来源:https://stackoverflow.com/questions/19244011/order-of-rewriterules-in-an-htaccess-file