任何人都知道如何让mod_rewrite在其规则中包含文件扩展名?

时间:2014-07-02 15:12:38

标签: php apache .htaccess mod-rewrite url-rewriting

我的重写规则是:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^([A-Za-z0-9_]*)/?$ index.php?a=$1 [NC]
RewriteRule ^([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/?$ index.php?a=$1&b=$2 [NC]
RewriteRule ^([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/?$ index.php?a=$1&b=$2&c=$3 [NC]

网址http://example.com/home/test/b将返回内部等效的index.php?a = home& b = test& c = b。虽然这很好(我昨天在这里试图让mod_rewrite工作),但我想在内部调用index.php这样的网址http://example.com/home/test/b.php?a = home& b = test& c = b。 PHP,而不是让Apache试图找到(失败)/var/www/home/test/b.php。我想让我的重写规则实际上处理所有文件扩展名。

2 个答案:

答案 0 :(得分:1)

如果您只想处理文件扩展名,可以手动执行,方法是更改​​最后一行:

RewriteRule ^([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*(\.[a-z]+)?)/?$ index.php?a=$1&b=$2&c=$3 [NC]

通过添加(\.[a-z]+)?,这会处理http://example.com/home/test/b.php,然后在var_dump($_GET);中为您提供index.php

array(3) { ["a"]=> string(4) "home" ["b"]=> string(4) "test" ["c"]=> string(5) "b.php" }

希望它有所帮助。

注意:它只会处理一个.,后面至少有一个[a-z]

如果您想处理http://example.com/home/test/b.test.php之类的内容,则需要:

RewriteRule ^([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/([A-Za-z0-9_]*(\.[a-z]+)*)/?$ index.php?a=$1&b=$2&c=$3 [NC]

答案 1 :(得分:1)

您可以使用:此代码:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^([\w.]+)/?$ index.php?a=$1 [L,QSA]
RewriteRule ^(\w+)/([\w.]+)/?$ index.php?a=$1&b=$2 [L,QSA]
RewriteRule ^(\w+)/(\w+)/([\w.]+)/?$ index.php?a=$1&b=$2&c=$3 [L,QSA]
字符类中的

[\w.]将允许[a-zA-Z0-9._]