简体   繁体   English

Apache htaccess 强制小写并删除斜杠

[英]Apache htaccess force lowercase and remove trailing slash

I am trying to redirect all URLs to lowercase and remove trailing slashes.我正在尝试将所有 URL 重定向为小写并删除尾部斜杠。

My htaccess file currently looks like this:我的 htaccess 文件目前看起来像这样:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond expr "tolower(%{REQUEST_URI}) =~ /(.*)/"
    RewriteRule [A-Z] %1 [R=308,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [R=308,L]
</IfModule>

This does work, however it does two redirects one after another.这确实有效,但是它会一个接一个地进行两次重定向。 First redirect forces lowercase and the second redirect removes the trailing slash.第一个重定向强制小写,第二个重定向删除尾部斜杠。

How can I merge these two rules into one redirect?如何将这两个规则合并为一个重定向?

You don't need to actually merge the two rules in order to reduce the number of redirects.您不需要实际合并这两个规则以减少重定向的数量。 You can reverse the order of the two rules and always convert the URL to lowercase in the rule that removes the trailing slash.您可以颠倒这两个规则的顺序,并在删除尾部斜杠的规则中始终将 URL 转换为小写。

For example:例如:

# Remove trailing slash AND convert to lowercase
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond expr "tolower(%{REQUEST_URI}) =~ m#(.+)/$#"
RewriteRule /$ %1 [R=308,L]

# Convert remaining URLs to lowercase
RewriteCond expr "tolower(%{REQUEST_URI}) =~ /(.*)/"
RewriteRule [A-Z] %1 [R=308,L]

A potential problem with combining the two rules (without adding additional complexity) is that you avoid converting URLs to lowercase that map to directories (which may or may not be an issue), since you can only remove the trailing slash on non-directories.结合这两个规则的一个潜在问题(不增加额外的复杂性)是您避免将 URL 转换为映射到目录的小写字母(这可能是也可能不是问题),因为您只能删除非目录上的尾部斜杠。

Note that I used the alternative regex-syntax in the first rule (formerly the second rule) in order to avoid having to escape literal slashes in the regex.请注意,我在第一条规则(以前是第二条规则)中使用了替代的正则表达式语法,以避免在正则表达式中转义文字斜杠。 The RewriteRule pattern can also be simplified now, since we only need to assert that the URL ends in a trailing slash. RewriteRule模式现在也可以简化,因为我们只需要断言 URL 以斜杠结尾。

Note that you should remove the <IfModule> wrapper if these directives are mandatory.请注意,如果这些指令是强制性的,则应删除<IfModule>包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM