Apache mod重写简单重定向

时间:2009-05-08 03:16:31

标签: regex apache mod-rewrite

我希望我网站的请求按以下方式运行:

http://example.com/会在不显示index.php的情况下提取index.php文件(当前的默认行为)

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

http://example.com/blerg会重定向到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

之外几乎可以工作

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

5 个答案:

答案 0 :(得分:3)

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

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

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

e.g。

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

答案 1 :(得分:1)

找到一个有效的解决方案

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/([^.]+)$ /bar.php?code=$1 [QSA,L]
http://example.com/ directs to index.php properly (without showing index.php)
http://example.com/abc directs to bar.php?code=abc
http://example.com/foo.php operates normally.

答案 2 :(得分:0)

假设这是在.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]

我认为它会解决它。

答案 3 :(得分:0)

在第二条规则前面使用RewriteCond指令,使其仅匹配您想要的网址,例如:

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

答案 4 :(得分:0)

添加拦截http://example.com/请求的规则,并阻止上一个规则运行:

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

我通常会将QSA(“查询字符串附加”)添加到我的规则中:[QSA,L]。

此规则集强制请求不存在的文件通过处理程序脚本:

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