Apache mod重写简单的redirect

我想请求我的网站工作如下:

http://example.com/将拉起index.php文件(当前的默认行为),理想情况下不显示index.php

http://example.com/foo.php会像预期的那样拉起foo.php

http://example.com/blerg会redirect到http://example.com/bar.php?code=blerg

我现在有以下重写规则

RewriteRule ^/(.*\.(php|html|htm|css|jpg))$ /$1 [NC,L] RewriteRule ^/(.*)$ /bar.php?code=$1 [NC,L] 

这几乎可以工作,除了http://example.com/拉起bar.php而不是index.php

理想情况下,我不会在第一条规则中有任何可能的文件扩展名,我宁愿只是检测它是否是一个实际的文件。

不是你所要求的我意识到,但我经常在.htaccess中使用它:

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php 

..发送任何不是实际的文件或目录到index.php,然后包含解释URL字符串中的任何内容的逻辑。

例如

 $url_array = split('/', $_SERVER['REQUEST_URI']); array_shift($url_array); // remove first value as it's empty 

找到一个可行的解决方案

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^/([^.]+)$ /bar.php?code=$1 [QSA,L] 
 http://example.com/正确地指向index.php(不显示index.php)
 http://example.com/abc指向bar.php?code = abc
 http://example.com/foo.php正常运行。

在第二条规则的前面使用RewriteCond指令,以便它只匹配所需的URL,例如:

 RewriteCond %{REQUEST_URI} ^/blerg$ RewriteRule ... 

添加拦截http://example.com/请求并阻止最后一条规则运行的规则:

 RewriteRule ^/(.*\.(php|html|htm|css|jpg))$ /$1 [NC,L] RewriteRule ^/$ /index.php [L] RewriteRule ^/(.*)$ /bar.php?code=$1 [NC,L] 

我通常将QSA(“query string append”)添加到我的规则中:[QSA,L]。

这个规则集强制请求到不存在的文件去处理一个处理程序脚本:

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ /handler.php?request=$1 [QSA,L] 

假设这是在.htaccess中,而不是Apache的conf文件,在重写规则的第一部分的前面没有/。 所以如果你想映射:

http://example.com/blah.jpg

你做:

 RewriteRule ^blah\.jpg$ /some_other_file.jpg [L] 

请注意缺少领先/和转义期(。),否则它匹配任何字符(如没有它,规则将匹配blahxjpg)。

另外,如果您重定向某个目录,则可能会发现客户端或服务器放置了一个斜杠。 为了处理它,我通常只是这样做::

 RewriteRule ^directory/?$ /some_other_directory/index.php [L] 

或类似的。

最后一点涉及到:

 RewriteRule ^/(.*)$ /bar.php?code=$1 [NC,L] 

基本上改为:

 RewriteRule ^/?(.*)$ /bar.php?code=$1 [NC,L] 

我想它会把它整理一下。