Apache .htaccess:如何向 URL 添加缺少的尾部斜杠但忽略文件和特殊 URL?

Apache .htaccess: How to add missing trailing slash to URLs but ignore files and special URLs?

由于我的 Web 项目有时会在缺少尾部斜杠时抛出 404,所以我总是希望我的服务器向 URL 添加尾部斜杠。因此,我在 .htaccess 中使用了以下模式:

# ################################## #
#      Redirect URLs which are not files to their trailing slash equivalent #
# ################################## #
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ // [L,R=301]

它看起来不错,但后来我意识到像

这样的链接

http://www.my-awesome-website.com/theme/base.css?ver=1995

正在转换为

http://www.my-awesome-website.com/theme/base.css/?ver=1995

这显然是不可取的,并且会导致网站崩溃。我该如何重写此规则,以便确定不包括对文件(.php、.jpg、.html 等)的任何请求?

您可以试试这个规则(假设您的非文件请求中没有点):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)([^./])$ %{REQUEST_URI}/ [L,R=301,NE]

确保在新浏览器中对此进行测试以避免旧缓存。