使用 .htaccess 删除 .php 扩展名而不破坏 DirectoryIndex [英] Remove .php extensions with .htaccess without breaking DirectoryIndex

查看:39
本文介绍了使用 .htaccess 删除 .php 扩展名而不破坏 DirectoryIndex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 .htaccess 文件中有以下重写,它从文件中删除了 .php 扩展名,例如将 so.com/question.php 转换为 so.com/question.

I have the following rewrite in my .htaccess file which removes the .php extension from files, converting for example so.com/question.php to so.com/question.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

然而,这也打破了默认的 DirectoryIndex 行为,在这种行为中,只需输入目录就会重定向到文件夹中的索引文件,例如so.com/answer 显示 so.com/answer/index.php

However this also breaks the default DirectoryIndex behaviour, in which just typing the directory will redirect to the index file in the folder, e.g. so.com/answer displays so.com/answer/index.php

简单地将上面的代码与 DirectoryIndex index.php 结合起来并不能达到这两个结果.

Simply combining the above code with DirectoryIndex index.php does not achieve both results.

谁能帮我把这两个函数结合起来,或者重写一下代码,排除index.php文件,也能达到同样的效果?

Can someone help me combine these two functions, or rewrite the code to exclude index.php files, which would achieve the same result?

推荐答案

我认为您只需要在重写之前验证文件是否存在,这样您就可以保持 404 和 directoryindex 行为不变:

I'm thinking you just need to verify that the file exists prior to doing the rewrite, that way you'll leave 404 and directoryindex behaviours intact:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

(未测试)

这篇关于使用 .htaccess 删除 .php 扩展名而不破坏 DirectoryIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆