.htaccess 不区分大小写的目录

.htaccess case-insensitive directories

我访问了file.php写作mydomain.com/file。我还需要能够访问写作 mydomain.com/FILE.

在 .htaccess 中,我使用以下规则删除扩展名:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ / [L,R=301]

RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^(.+?)/?$ /.php [L]

# redirect to .php-less link if requested directly
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP/.+
RewriteRule ^(.+)\.php  [R=301,L]

是否应更改此规则 - 由您决定。

在您的规则中使用 [NC] 标志

Use of the [NC] flag causes the RewriteRule to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI.

https://httpd.apache.org/docs/current/rewrite/flags.html

您需要注意两个方面:首先是不区分大小写的匹配,其次是将大小写转换为小写。

Apache 的重写模块为第一个方面提供了 NC 标志,为第二个方面提供了更复杂的方法:

RewriteEngine On

# remove trailing slash (/) if no such folder exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /${lc:}  [NC,L,R=301]

# internally rewrite to a php script if it exists and convert to lower case
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /${lc:}.php [NC,L]

# redirect to .php-less link if requested directly
RewriteRule ^(.+)\.php$ ${lc:}  [NC,L,R=301]

我的印象是,您最初的重写规则集并没有真正实现您的目标,甚至在语法上也是无效的。这就是为什么我改变了几个方面。

在 Apache 或 vhost 配置中定义此 RewriteMap

RewriteMap lc int:tolower

然后在你的 .htaccess 中有一个额外的规则来小写所有大写的 URIs:

RewriteEngine On

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

# redirect to .php-less link if requested directly
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.php\sHTTP [NC]
RewriteRule ^(.+)\.php$ / [R=301,L,NC,NE]

# convert each REQUEST_URI to lowercase
RewriteRule ^(.*?[A-Z]+.*)$ /${lc:} [R=301,L,NE]

# internally add .php 
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^(.+?)/?$ .php [L]