Order of RewriteRules in an htaccess file

做~自己de王妃 提交于 2021-02-05 08:49:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!