mod_rewrite:将顶级目录重定向到文件

时间:2010-07-13 19:28:45

标签: regex apache .htaccess mod-rewrite

我想使用mod_rewrite将所有顶级目录重定向到一个文件。

所以以下内容应该重定向:

- http://example.com/test
- http://example.com/test8/ 
- http://example.com/test_9231/

以下内容不应重定向:

- http://example.com/test.php
- http://example.com/test_9231/test/
- http://example.com/test/test.php
- http://example.com/test_9231/test

所有目录都不会存在。目录名称仅包含以下字符:A-Za-z0-9_-

我尝试了这个RewriteRule /(.*) /index.php [L]但子目录仍然被重定向 我想在第二个括号之后添加一个斜线就能完成这项工作,但它只是打破了重定向。

2 个答案:

答案 0 :(得分:2)

RewriteRule ^/[A-Za-z0-9_-]+/?$ /index.php

这将匹配斜杠,然后根据您的规范匹配,然后是另一个可选斜杠,然后是字符串结尾,因此子目录将不匹配

答案 1 :(得分:0)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?[^/]+/?$ /index.php [L]
相关问题