php - 当前对 apache/php 的设置将始终返回 200 页而不是 404
问题描述
更新:我添加了一个 404 错误文档:
<IfModule mod_rewrite.c>
RewriteEngine on
ErrorDocument 404 /new404.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</IfModule>
但一切都没有改变。
我对 apache 片段有疑问:
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
在
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</IfModule>
我创建了一个这样的 URL:
http://localhost:8888/en
http://localhost:8888/en/team
http://localhost:8888/en/anything
我这样调用我的 PHP 文件:
team-en.html.php
anything-en.html.php
这是因为我有不同的语言。
现在,这是我的 PHP 文件来显示它们:
$path = isset($_GET['path']) ? $_GET['path'] : false;
$path = strtolower($path);
$path = preg_replace("/[^a-z-\/]/", '', $path);
$parts = explode("/", $path);
if (is_array($parts) && isset($parts[1])) {
if (file_exists(__DIR__ . '/processors/' . $parts[1] . '.php')) {
$processor = $parts[1];
}
if (file_exists(__DIR__ . '/pages/' . $parts[1] . '-'. $language .'.html.php')) {
$page = $parts[1];
}
}
其中语言变量是:
$language = 'en';
$languages = [];
$languages[] = 'en';
$languages[] = 'nl';
$languages[] = 'fr';
现在,由于某种原因,这不会返回 404 页面,只会返回 200 标头响应。
我想知道是否有人有设置 404 页系统的经验,我阅读了很多教程,但没有一个给我满意的答案。
先感谢您
解决方案
重写规则匹配所有路由。Apache 不可能抛出 404 错误,因为它不知道您的应用程序在做什么。
您需要在 PHP 代码中检查是否应在应用程序本身中引发此类错误。如果子文件夹中的文件适合于此,您可以编写:
if (is_array($parts) && isset($parts[1])) {
if (file_exists(__DIR__ . '/processors/' . $parts[1] . '.php')) {
$processor = $parts[1];
}
if (file_exists(__DIR__ . '/pages/' . $parts[1] . '-'. $language .'.html.php')) {
$page = $parts[1];
} else {
http_response_code(404);
die();
}
}
推荐阅读
- python - numpy where - 如何在整列上设置条件?
- mysql - NiFi PutDatabaseRecord 处理器面临错误,无法创建 PoolableConnectionFactory(无法创建与数据库服务器的连接)
- python - Flask:在多个路线中使用文件
- asp.net-core - 无法替换 ASP.Core 3 中的默认 JSON 合同解析器
- github - 打印整个 github 存储库
- swift - 如何在形状层中居中 CAShapeLayer 路径
- java - Sonarqube 使用 Cobertura 而不是 Jacoco
- python - 对 dask 数据帧进行分区并将其转换为 pandas 数据帧的最佳方法是什么?
- python - 改进随机选择:Python 子网掩码生成器
- css - 如何将模态框放在 b-dropdown 下方的子组件中,并且不会在 b-dropdown 内呈现?