首页 > 解决方案 > 当前对 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 页系统的经验,我阅读了很多教程,但没有一个给我满意的答案。

先感谢您

标签: phpapachefile-not-founderrordocument

解决方案


重写规则匹配所有路由。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();
    }       
}

推荐阅读