RewriteRule htaccess总是删除尾随斜杠甚至目录

1 php apache .htaccess mod-rewrite rewrite

目标是结合几个规则:

  • URI中永远不会有尾部斜杠
  • 调用domain.tld/somedir时,在内部重写到index.php(domain.tld/somedir/index.php)
  • 删除文件扩展名,检查是否存在+'.php'并最终在内部重写它

这是在'.htaccess'中完成的,因为这是我唯一可访问的.

到目前为止我的尝试

# check if *.php exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*[^/])/?$ $1.php [L, QSA]

# do not allow trailing slash
RewriteRule (.*)/ $1 [L, R=301]
Run Code Online (Sandbox Code Playgroud)

这里的困难是查询'domain.tld/somedir'在被重定向到'domain.tld/somedir /'之后通常会调用目录的index.php.但是,我想在查询'domain.tld/somedir'时直接在内部调用index.php(没有301).

anu*_*ava 5

您可以使用此代码:

DirectoryIndex index.php
RewriteEngine On

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]
Run Code Online (Sandbox Code Playgroud)

  • 这对我来说是最好的解决方案 (2认同)