如何为mod_rewrite中的每个规则添加一些前缀?

时间:2016-05-19 17:05:31

标签: php apache .htaccess mod-rewrite

我在mod_rewrite中有很多规则。目前我们决定在我们的网站上添加第二种语言。那么,如果url中有一个规则,有没有办法为每个规则添加一些前缀?例如,我有下一个规则:

RewriteRule ^addorder/?$ add_order.php
RewriteRule ^order/?$ order.php

所以,如果我有下一个链接http://test.com/addorder/,那么我应该去

RewriteRule ^addorder/?$ add_order.php

如果我有下一个链接http://test.com/en/addorder/,那么我应该去

RewriteRule ^addorder/?$ add_order.php?lang=en

正如我所说,我不想复制这样的规则,因为它们有很多

RewriteRule ^addorder/?$ add_order.php
RewriteRule ^/en/addorder/?$ add_order.php?lang=en
RewriteRule ^order/?$ order.php
RewriteRule ^/en/order/?$ order.php?lang=en

1 个答案:

答案 0 :(得分:1)

您可以通过在没有lang标记的单独规则中首先处理L组件来避免重复类似规则:

RewriteEngine On

# handle lang parameter (this rule will be followed by rules below)
RewriteRule ^([a-z]{2})/(.+)$ $2?lang=$1 [QSA]

# specific rules to corresponding .php files
RewriteRule ^addorder/?$ add_order.php [L,NC]

# generic catch all .php handler for order -> order.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]