尝试使用 .htaccess 文件删除 .php 扩展名时出现 403 禁止错误

I get a 403 forbidden error when trying to remove the .php extension using .htaccess file

我想使用与 php 文件位于同一文件夹中的 .htaccess 文件从 URL 中删除 .php 扩展名(我想删除 php 文件的扩展名所有文件,而不仅仅是其中一个)。我使用以下代码:

Options +FollowSymLinks # I found this on the Internet trying to solve this problem, but nothing changed
RewriteEngine On
RewriteBase /app_tests/ # This is the folder where I want to delete the .php extension, it's located in the htdocs folder
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L] #I have tried without QSA as well (I don't really know what it does)

所以理论上,当我访问 myweb.com/index 时,我应该会看到 index.php 页面,但在输入该地址时出现 403 错误(禁止访问)。当然,没有名为 index 的目录。我知道代码有效(或至少做了一些事情),因为当我写错它时它说内部服务器错误并且因为如果我擦除或评论它(#)我得到的错误是 404(未找到)。

我正在为 Windows 使用 XAMPP 的最新版本之一。我已经取消注释 httpd.conf 文件中的以下行以加载模块:

LoadModule rewrite_module modules/mod_rewrite.so

有谁知道我做错了什么或如何解决这个问题?谢谢!

它可能失败了,因为你在指令后面有注释。在 .htaccess 中,注释必须独占一行,不能在 rule/condition.

之后

我将通过分享我的堆栈中的一个片段来帮助您完成手头的任务。将此 .htaccess 文件放入您希望 .php-less 文件访问起作用的文件夹中。

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
RewriteBase /app_tests/

# Set an S for HTTPS protocol
# helps for rewrites with protocol specific URL
RewriteCond %{SERVER_PORT}s ^(443(s)|[0-9]+s)$
RewriteRule ^(.+)$ - [ENV=SFORSSL:%2]

# remove trailing slashes if it's not a directory
# you will need this, because if a trailing slash is added wrongly
# the condition for the next group of rules will fail
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ http%{ENV:SFORSSL}://%{HTTP_HOST}/ [R=301,QSA,L]

# internally rewrite to .php if a file exists
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.+) .php [QSA,L]
</IfModule>

QSA,代表Query String Append,它基本上是将GET请求包含的所有请求参数附加到URL(URL中?之后的所有内容)。