php - PHP - 为不存在的文章加载 404 页面而不更改 URL
问题描述
我知道这方面有很多类似的问题,我已经阅读过它们,但它们没有用。我想在我的网站上访问不存在的动态 url 但不更改 url 时显示 404 页面。例如:
https://www.trvme.com/destinations/corbett
很好。但是如果我输入一个无效的链接,比如
https://www.trvme.com/destinations/corbetts
我收到浏览器的 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]
解决方案
推荐阅读
- amazon-web-services - 如何禁用 AWS CLI 帮助输出的分页?
- javascript - 是否可以检测是否使用 JavaScript / Laravel 扫描了二维码?
- c - 当您使用 MPI_STATUS 接收消息时,MPI 找出发件人
- javascript - 如何在一行中将 iife oldways 函数转换为箭头函数
- php - PHP 函数“resize”和“fit”不起作用
- python - 图像转换 python
- mysql - 在mysql中为数据库中的每个表创建具有最大值的视图
- junit - MariaDB 连接随机失败但稳定
- excel - 是否有一种有效的方法可以通过匹配单元格将数据从一张表更新到另一张表
- html - Django 无法从 css 添加背景图片