[英]PHP - Load 404 page for non existing articles wihout changing 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.