【发布时间】:2020-06-14 01:36:12
【问题描述】:
我有一个项目,其中所有请求都通过 .htaccess 文件中的路由发送到 index.php。
不幸的是,这在 XAMPP Virtualhost 中不起作用。
但是当我转到根文件夹并执行命令 PHP -S 127.0.0.1:8080 或任何其他端口时,路由系统工作并且 .htaccess 文件也工作.
这证明我的 PHP 代码没有任何问题。
澄清一下:我可以到达虚拟主机并且它确实有效。
但是当我添加/control 时,它会显示“找不到对象”,因为control.php 不存在。但它应该将我带到控制页面,因为它应该将请求发送到index.php。
.php 扩展名删除确实有效,所以/client 确实有效,因为有一个名为client.php 的文件。所以 .htaccess 并没有被忽略。
我还尝试在 .htaccess 文件中输入一些随机内容,看看它是否会给我一个服务器错误,并且确实如此。这也证明了 Virtualhost 不会忽略 .htaccess 文件。
我的 .htaccess 文件:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ /index.php?q=$1 [NC,L,QSA]
httpd-vhosts.conf 文件:
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs/example"
ServerName example.com
ServerAlias www.example.com
<Directory "C:\xampp\htdocs\example">
AllowOverride All
</Directory>
</VirtualHost>
有人知道这个问题的解决方案吗?
此致,
编辑 1
我在httpd-vhosts.conf 中添加了DirectoryIndex index.php 行,它知道看起来像这样:
<Directory "C:\xampp\htdocs\example">
DirectoryIndex index.php
AllowOverride All
</Directory>
编辑 2
经过一些测试,我发现/login 的路由规则确实有效。
我的index.php 文件:
<?php
// For Routing, I use the library AltoRouter: https://altorouter.com/
session_start();
require '../vendor/autoload.php';
require __DIR__ .'/includes/PHP/logout.inc.php';
$router = new AltoRouter();
$router->map('GET', '/', function() {
require __DIR__ . '/homepage.php';
});
$router->map('GET', '/405', function() {
echo '405';
});
$router->map('GET', '/login', function() {
require __DIR__ . '/login.php';
});
$router->map('GET', '/beheer', function() {
require __DIR__ . '/beheer.php';
});
$router->map('POST', '/uitloggen', function() {
$confirmation = TRUE;
logout($confirmation);
});
$router->map('GET', '/client/[i:id]', function() {
require __DIR__ ."/client.php";
});
$router->map('GET', '/car/*', function() {
require __DIR__ . "/auto.php";
});
$match = $router->match();
if(is_array($match) && is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
} else {
echo '404';
}
当我将/login 的规则更改为echo 'login' 时,它实际上打印了“登录”消息,所以这也证明它有点工作,但由于某种原因并不完全。
当我将/beheer 规则更改为/control,(control.php 存在),然后我将require __DIR__ . '/control.php 行更改为echo 'control,它会打印“控制”消息。
因此,如果 url 中的路径有效且存在,XAMPP 似乎只重定向到index.php。
有什么办法可以解决这个问题?
编辑 3 和解决方案
过了一会儿,我意识到我也可以发送所有 404 错误 index.php 文件,然后我会处理 index.php 文件中真正的 404 错误。
所以我只是在.htaccess 文件中添加了:ErrorDocument 404 index.php。
【问题讨论】:
-
听起来你忘记设置 index 模块提供的
DirectoryIndex指令来考虑你的index.php路由脚本:httpd.apache.org/docs/2.4/mod/mod_dir.html -
@arkascha 我已经在 ```httpd-vhosts.conf```` 中设置了
DirectoryIndex,但它仍然不起作用。
标签: php apache .htaccess routing xampp