尾随斜线

时间:2009-06-12 08:24:35

标签: apache mod-rewrite

如何添加尾部斜杠:

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php

我尝试过:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+[^/])$ $1/ [R]

但它不起作用

2 个答案:

答案 0 :(得分:3)

请参阅CondPatterns -d的详细信息/描述行以及RewriteCond的-f。看看它是如何“测试它是否存在,并且是一个常规文件”?这很昂贵,根本不能很好地扩展。如果它是“常规文件”,你真的在​​乎吗?不,你只关心看起来像文件一样(匹配filename.extension模式)所以,当我在它的时候,我会改进你的重写。

请参阅RewriteRule的“last | L”标志的详细信息/说明。看看它怎么说“不再应用任何重写规则”?我敢打赌那就是你想要的不是吗?您希望在请求与静态资产的扩展名不匹配时使用 index.php, OR 您希望在请求的末尾添加斜杠与filename.extension模式不匹配。不是两个。

这是你如何做到的:

# turn on matching
RewriteEngine on

# 1st rule block. If any of the conditions don't apply skip over this block to the next.
# condition: uri ends with filename.extension
RewriteCond %{REQUEST_URI}  [^/.]+\.[^/.]+$
# condition: uri doesn't end with a desired extension
RewriteCond %{REQUEST_URI}  !\.(js|ico|gif|jpg|png|css|html)$ [NC]
# rewrite the request to be for index.php and don't apply any more rules
RewriteRule -  index.php [L]

# 2nd rule block. If any of the conditions don't apply skip over this block to the next.
# condition: uri doesn't end with a slash
RewriteCond %{REQUEST_URI}  !/$
# condition: uri doesn't end with filename.extension
RewriteCond %{REQUEST_URI}  !/[^/]+\.[^/.]+$
# rewrite the request to be appended with a slash
RewriteRule (.*)  $1/ [R=301]

考虑到你没有告诉我们你想要做什么,这是一个非常好的答案。如果你想要一个更好的答案,你需要给我们提供更多的信息,而不是“我复制并粘贴了两个代码snipets,但它不起作用。”


更新:根据cornegigouille的回答,我匆匆把这个答案编辑到了一起。这是我测试它的证据的bash shell脚本。如果你看到一个错误,请告诉我。

#bruno:~$ (
for str in asdf asdf.css asdf.min.css; do
    echo -e "\n## $str ##"
    echo /brunobronosky1/$str | grep -E '/[^/.]+\.[^/.]+$' || echo '[no match]'
    echo /brunobronosky2/$str | grep -E '/[^/]+\.[^/.]+$' || echo '[no match]'
    echo /cornegigouille/$str | grep -E '/[^/.]+(\.[^/.]+)+$' || echo '[no match]'
done
)

## asdf ##
[no match]
[no match]
[no match]

## asdf.css ##
/brunobronosky1/asdf.css
/brunobronosky2/asdf.css
/cornegigouille/asdf.css

## asdf.min.css ##
[no match]
/brunobronosky2/asdf.min.css
/cornegigouille/asdf.min.css

答案 1 :(得分:1)

布鲁诺的答案很棒,但不完整 它没有解决文件名包含多个点的情况。这在您开始使用缩小时非常常见(例如 www.mysite.com/css/styles.min.css )。

第二个规则块的第二个条件应该是:

# condition: uri doesn't end with filename.extension
RewriteCond %{REQUEST_URI}  !/[^/.]+(\.[^/.]+)+$