首页 > 解决方案 > PHP - 为不存在的文章加载 404 页面而不更改 URL

问题描述

我知道这方面有很多类似的问题,我已经阅读过它们,但它们没有用。我想在我的网站上访问不存在的动态 url 但不更改 url 时显示 404 页面。例如:

https://www.trvme.com/destinations/corbett

很好。但是如果我输入一个无效的链接,比如

https://www.trvme.com/destinations/corbetts

我收到浏览器的 404 错误,但没有看到我的 404 页面。 404错误 这是我在 PHP 中的代码

if(isset($_GET['destId'])){
    $link = mysqli_real_escape_string($connect, $_GET['destId']);
    $thisPage = 'destinations/'.$link;

    $query = "SELECT * FROM `destinations` WHERE `link` = '$link' AND `active` = 1 AND `delete` = 0";
    $destinationsQuery = mysqli_query($connect, $query);
    if(mysqli_num_rows($destinationsQuery)!=0){
        // do stuff
    } else {
        http_response_code(404);
        exit();
    }
} else {
    http_response_code(404);
    exit();
}

和 htaccess

RewriteEngine On

ErrorDocument 404 /message.php?id=2

RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]

我不想header('location:message.php?id=2');在 php 中使用,因为那会改变 URL。我从 URL 获得 404 代码,但 htaccess 似乎没有完成它的工作。

我也不能用

http_response_code(404);
include 'message.php';

因为它会引发各种错误,例如会话已经开始并且已经定义了常量。这似乎不是一个优雅的解决方案。

编辑:

链接问题中的代码对我不起作用。如果我在目标规则上方添加代码,现有的合法页面也会转到 404,因为没有实际的文件或目录,这些是动态 url。

RewriteEngine On

ErrorDocument 404 /message.php?id=2

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]

RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]

如果我把它放在之后,它就不起作用,因为目的地规则接管了

RewriteEngine On

ErrorDocument 404 /message.php?id=2

RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]

标签: php.htaccess

解决方案


如果您想要一个特定的 404,您需要捕获它或创建在 apache 中加载的 404 HTML。

看:捕获所有无效的 URL

他们建议在 apache 中使用 ErrorDocument。


推荐阅读