【问题标题】:I get a 403 forbidden error when trying to remove the .php extension using .htaccess file尝试使用 .htaccess 文件删除 .php 扩展名时出现 403 禁止错误
【发布时间】:2018-07-28 23:08:03
【问题描述】:

我想使用与 php 文件位于同一文件夹中的 .htaccess 文件从 URL 中删除 .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

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

【问题讨论】:

    标签: apache .htaccess mod-rewrite xampp httpd.conf


    【解决方案1】:

    它可能失败了,因为指令后面有 cmets。在 .htaccess 中,cmets 必须在自己的行中,它们不能出现在规则/条件之后。

    我将通过分享我的堆栈中的 sn-p 来帮助您完成手头的任务。将此 .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}/$1 [R=301,QSA,L]
    
    # internally rewrite to .php if a file exists
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule (.+) $1.php [QSA,L]
    </IfModule>
    

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

    【讨论】:

    • 我不知道.htaccess 中的评论规则,谢谢。无论如何,我在这里粘贴代码时写了那些cmets。您的代码对我不起作用(我收到 404 not found 错误)...也许是 httpd.conf 配置错误?我取消了 [LoadModule rewrite_module modules/mod_rewrite.so] 行的注释,够了吗?谢谢!!
    • @JorgeBruned 现在检查一下,我更新了我的代码以考虑到您的重写基础。
    • 非常感谢,现在一切正常!最后一个问题,现在我的 URL 看起来像 mywebsite.com/app_tests/index(.php) // mywebsite.com/app_tests/app/alumnos(.php),但是如果域是“mywebsite.com”,我如何从 URL 中删除“app_tests”文件夹(如果它不是例如“yourwebsite.com” “)?我做不到。再次感谢!
    • @JorgeBruned 我想您正在测试环境中工作。你现在不应该担心这个。当您将代码放在域的根目录上时。它只适用于您的根网站,例如 mywebsite.com/index。
    • 实际上我不是在测试环境中工作,“测试”这个词是我完成的网络应用程序名称的一部分。问题是我想在一个 Web 服务器中拥有多个网站,所以我想从 URL 中删除文件夹的名称,只要域是“mywebsite.com”。如果它太复杂甚至不可能,我想知道如何从 URL 中删除一个文件夹(没有任何条件)。谢谢你:)
    猜你喜欢
    • 2023-03-22
    • 2016-10-22
    • 2014-10-09
    • 2012-05-14
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2011-04-30
    相关资源
    最近更新 更多